我正在创建一个具有mongo后端的投票系统,并且试图弄清楚在进行投票后如何更新前端的号码。现在,该数字正在通过车把动态显示。在.up上,单击ajax即可,然后将数据发送到服务器,然后返回gameData。基本上,我希望我的{{currentvote}}号在成功时可以更新。
$('.up').on('click', function() {
var id = this.id;
$.ajax({
type: "POST",
url: "/api/upvote",
data: JSON.stringify({ cardId: id }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(gameData){
console.log(gameData.currentvote + 1);
},
failure: function(errMsg) {
alert(errMsg);
}
});
});
<div class="col-lg-12">
<div class="row">
<div class="up" id="{{ID}}"><i class="fas fa-chevron-circle-up color-gray upvote"></i></div>
<div class="down" id="{{ID}}"><i class="fas fa-chevron-circle-down color-gray downvote"></i></div>
<div class="margin-left"><p class="vote-number" id="green">{{currentvote}}</p></div>
</div>
</div>
答案 0 :(得分:1)
当您在jquery ajax中进行操作时,您也应该通过jquery完成它。您可以像这样轻松地做到这一点:
success: function(gameData){
var currentVote = $(".vote-number").text();
$(".vote-number").text( parseInt(currentVote) + parseInt(gameData.currentvote) + 1 );
}
答案 1 :(得分:-1)
普通的老JS应该做的。
$('.up').on('click', function() {
var id = this.id;
var upVote = document.getElementById('green');
$.ajax({
type: "POST",
url: "/api/upvote",
data: JSON.stringify({ cardId: id }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(gameData){
console.log(gameData.currentvote + 1);
upVote.innerText= parseInt(upVote.innerText) + 1;
},
failure: function(errMsg) {
alert(errMsg);
}
});
});
编辑:已更新,以考虑Brad的评论。