我正在开发一个包含带有“喜欢”和“不喜欢”的评论功能的应用程序,就像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,他/她的建议很有启发性!现在,我已经使其正常工作。