簡體   English   中英

如何使用AJAX成功函數更新動態創建的號碼?

[英]How do I update a dynamically created number with an AJAX success function?

我正在創建一個具有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>

當您在jquery ajax中執行此操作時,您也應該通過jquery完成它。 您可以像這樣輕松地做到這一點:

success: function(gameData){
    var currentVote = $(".vote-number").text();
    $(".vote-number").text( parseInt(currentVote) + parseInt(gameData.currentvote) + 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);
        }
    });
});

編輯:更新以考慮布拉德的評論。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM