我正在建立一个网站,用户可以喜欢,喜欢按钮是工作,它是存储在数据库中的喜欢。我的问题是,我如何才能让用户再次点击like按钮时,它会在数据库上减去。我有一个动画的喜欢按钮,第一个默认的状态是它是灰色的,然后当用户点击它时,它会变成蓝色,旁边会出现一个“喜欢”的文本。然后,当用户再次单击时,它将恢复为黑色。
下面是我关于POST路由的代码(因为我正在向数据库添加数据)
app.post("/index/:id", function(req,res){
TestData.findById(req.params.id, function(err, theUser){
if(err){
console.log(err);
} else {
theUser.likes += 1;
theUser.save();
console.log(theUser.likes);
}
});
});
我的EJS文件:
<a class="likeicon" href="/index/<%= newUsers._id %>?_method=POST">
<i class="fa fa-thumbs-o-up" aria-hidden="true" ></i>
</a>
和我的jQuery:
$(".likeicon").on('click', function(){
if($(this).css("color") === "rgb(0, 0, 255)"){
$("#likedtxt").remove();
$(this).css("color", "black");
$(this).animate({fontSize: "15px"});
} else {
$(this).css("color", "blue");
$(this).append("<span id='likedtxt'>Liked</span>");
$(this).animate({fontSize: "18px"});
}
});
还有一个问题,当我点击点赞时,它正在添加到数据库中,但我如何在用户屏幕上实时显示点赞计数更新?而无需重新加载屏幕。因为我不想使用res.redirect,所以它会刷新网页。
发布于 2016-09-22 11:31:28
更好的是,你可以把onclick函数写成"likeicon“按钮
<a class="likeicon" userId="<%= newUsers._id %>" onclink="updateLikes()">
<i class="fa fa-thumbs-o-up" aria-hidden="true" > 49 </i>
</a>
功能:
function updateLikes() {
id = $('.likeicon').attr('userId');
$.post('/index/' + id, function (response) {
$('fa-thumbs-o-up').text(response.likeCount); //your counter on a page
//and update likes counter with response
})
}
和node.js
app.post("/index/:id", function (req, res) {
TestData.findById(req.params.id, function (err, theUser) {
if (err) {
console.log(err);
} else {
theUser.likes += 1;
theUser.save();
console.log(theUser.likes);
res.send({likeCount: theUser.likes}); //something like this...
}
});
});
发布于 2016-09-22 11:31:58
对于更新的点赞计数,你应该从服务器发送更新的点赞计数,例如:
app.post("/index/:id", function(req,res){
TestData.findById(req.params.id, function(err, theUser){
if(err){
console.log(err);
return res.status(500).send('Something went wrong!'); // You should notify user about any error
} else {
theUser.likes += 1;
theUser.save(function(err){
if(err) return res.status(500).send('Something went wrong!');
return res.send({likes_count: theUser.likes});
});
}
});
});
发布于 2019-12-26 04:00:09
从前端发送值不是一个好主意...
相反,您可以使用MongoDB内置操作=> '$inc‘
其递增mongoose对象模型的字段中的值。
router.post('/:id',(req,res,next)=>{
counter = req.body.like;
TestData.update({_id:id},{$inc:{likes:counter}}).exec()
.then(result=>{
res.status(200).json({message:'liked'});
}).
catch(err=>{
res.status(500).json({error:err});
});
});
如果发送req.body.likes = 1,则like字段的值加1。
如果它是负的,那么它就会递减。
https://stackoverflow.com/questions/39637482
复制相似问题