我正在构建一个博客站点,当数据库中存储了超过 3 个帖子时,我尝试使用分页来浏览博客帖子的页面。单击“更新”或“上一个”按钮到后端以控制页面时,我试图从前端传递数据。我该怎么做呢?
我觉得我必须以某种方式使用 POST 方法。
这是我在 EJS 中的前端代码。这些是控制帖子页面的按钮。
<% if(totalItems > 3){ %>
<div class="page-buttons">
<form action="/">
<button type="submit" class="btn btn-outline-info newer-posts">Next</button>
<button type="submit" class="btn btn-outline-info older-posts">Previous</button>
</form>
</div>
<% } %>
这是后端的路由。
app.get("/", (req, res) => {
let currentPage = req.query.page || 1;
let perPage = 3;
let totalItems;
Post.find()
.countDocuments()
.then(count => {
totalItems = count;
Post.find()
.skip((currentPage - 1) * perPage)
.limit(perPage)
.then(posts => {
res.render("home", {
posts: posts,
totalItems: totalItems
});
});
})
});
我希望单击按钮会增加或减少 currentPage
变量,并从后端呈现适当的博客文章页面。但相反,它什么都不做。
如有任何帮助,我们将不胜感激。
最佳答案
因为您知道项目(博客文章)的总数,您可以做一些简单的数学运算来知道最后一页是什么。
const lastPage = Math.ceil(totalItems / perPage);
就像你路过posts
和 totalItems
, 我也会通过 currentPage
和 lastPage
.我们基本上可以在模板中执行上述数学运算,但我们为什么要这么做?
res.render("home", {
posts,
currentPage,
totalItems,
lastPage
});
// The above notation is shorthand for prop: value
现在,在模板中,我们可以根据传递的变量来决定是否显示上一页和下一页按钮。
如果currentPage
大于 1,我们必须在第二页或之后,所以显示当前页的链接 ?page=<%= currentPage - 1 %>
.
如果currentPage
低于lastPage
,我们还没有到达终点,所以我们显示下一页的链接。这将是 ?page=<%= currentPage + 1 %>
这里不需要使用表格。简单 <a>
标签就足够了。
关于javascript - 如何添加分页以导航博客文章页面(Node/Express),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55703901/