首页 > 解决方案 > 为什么我需要刷新页面才能获取新更新的数据?

问题描述

我正在制作一个应用程序,其中包括带有“喜欢”和“不喜欢”的评论功能,就像 Facebook 一样。但是我发现当用户点击“喜欢”或“不喜欢”的按钮时,一切都很顺利——数据库已经更新,新数据已经返回到以前的网页,除了用户需要手动刷新页面来获取具有新更新数据的新网页。这是我的文件(我只是以“like”函数的代码为例,“dislike”函数的代码是一样的):

JS代码:

$("#scrollit").on("click", ".fa-thumbs-up", function(){
var numberOfLikes = Number($(this).next().html());
var numberOfDislikes = Number($(this).next().next().next().html());
numberOfLikes = numberOfLikes + 1;
var Text = $(this).next().next().next().next().next().html();
console.log(Text);

$.ajax({
    method: "POST",
    url: "/searchresult/comments/likes",
    data: {text:Text, likes: numberOfLikes, dislikes: numberOfDislikes}
});
});

Node.js 代码:

app.post("/searchresult/comments/likes", function(req, res) {
var likes = req.body.likes;
var Text = req.body.text;

new Promise(function(resolve, reject) {
        comments.update({text: Text}, {$set: {likes: likes}}, function(err){
            if (err) {
                console.log(err);
            } else {
                console.log("Likes update successfully!");
                resolve(comments);
            }
        });
}).then(function(r){
    console.log("DONE!");
    res.redirect("/searchresult");
});
});


app.get("/searchresult", function(req, res){
var EnglishofWord = EnglishofWords[EnglishofWords.length - 1];
grewords.findOne({English: EnglishofWord}).populate("Comments").exec(function(err, allgrewords){
    if (err) {
        console.log(err);
    }   else {
        console.log(allgrewords);
        if (allgrewords == null || allgrewords.length < 1 || allgrewords == undefined ) {
            console.log("We don't have this word in dictionary!");
            res.render("errorpage");
        } else {
            res.render("searchresult", {greword:allgrewords});
        }
    }
});
});

ejs代码:

<% greword.Comments.forEach(function(comment){ %>
                    <strong><p class="author"><%= comment.author %></p></strong>
                    <i class="far fa-thumbs-up"></i><span class="likes"><%= comment.likes %></span>
                    <i class="far fa-thumbs-down"></i><span class="dislikes"><%= comment.dislikes%></span>
                    <span class="pull-right">10 days ago</span>
                    <p><%= comment.text %></p>
                    <% }) %>

有人可以帮我弄清楚吗?---- 为什么网页不自动刷新?非常感谢!:P

//************************************************更新!****************************************************** *//

非常感谢 t3__rry,他/她的建议很有启发性!现在我已经让它正常工作了。

标签: node.jspostgetrefreshejs

解决方案


推荐阅读