node.js - 为什么我需要刷新页面才能获取新更新的数据?
问题描述
我正在制作一个应用程序,其中包括带有“喜欢”和“不喜欢”的评论功能,就像 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,他/她的建议很有启发性!现在我已经让它正常工作了。
解决方案
推荐阅读
- android - 我的敏 Android Sdk 14 但我的应用无法在 android 6.0 及更早版本上运行?
- excel - 将行号动态传递给 Session.findbyid 方法
- angular - 带有 forRoot 和 AOT 的 Angular 6 库 - 装饰器不支持函数调用
- matlab - 如何合并结构中的冗余字段?
- typescript - NativeScript/TypeScript:找不到命名空间“android”
- angular - 重置响应式表单会触发 Angular 6 中所有必需的验证器
- c# - 如何将 XML 属性反序列化为对象,然后遍历对象
- xcode10 - 方案的应用程序语言设置
- java - 在 Spring Boot 中创建新的实体对象
- c++ - 从 /etc/ld.so.conf 使 ld 忽略目录