如何使用带有nodejs的ajax加载更多帖子

时间:2018-02-10 02:54:15

标签: node.js ajax

我正在尝试在我网站的索引页面上加载更多帖子。我想出了类似的东西

对后端执行AJAX调用以更改mysql查询限制的按钮:

    $("body").on('click','#loadMore',function(){ 
    var loadMoreBtn = $('#loadMore');
    var ajaxLimit = 5;
        $.ajax({
            url: '/',
            method: 'POST',
            //dataType: 'application/json',
            data:{ajaxLimit:ajaxLimit},
            success: function(response){ 
            console.log("limit changed")
            }
        });
});

在后端我有一个名为limit的变量,我将ajaxLimit添加到:

app.get("/", function(req, res){
var ajaxLimit = req.body.ajaxLimit;
var limit = 10 + ajaxLimit ;

var q ="SELECT posts.post_title, posts.image, posts.post_description, posts.id, DATE_FORMAT(posts.created_at, '%m/%d/%Y') AS created_at, users.avatar, users.username, (SELECT COUNT(*)  FROM comments WHERE comments.post_id = posts.id) AS NumberOfComments, (SELECT COUNT(*)  FROM likes WHERE likes.post_id = posts.id) AS NumberOfLikes FROM posts INNER JOIN users ON posts.user_id=users.id ORDER BY posts.created_at DESC LIMIT "+ limit + "";
connection.query(q, function(err, results) {
    if (err) throw err;
    var post_id = results[0].id;
    res.render("t_index",{posts:results});
});
});

接下来我要做的是将新帖子附加到当前视图。但我无法改变限制,我相信我做错了吗?

1 个答案:

答案 0 :(得分:1)

您的参数 req.body.ajaxLimit 以字符串形式出现,因此将其强制转换为int以获得所需的限制。

var ajaxLimit = parseInt(req.body.ajaxLimit)