防止多个ajax帖子

时间:2017-04-02 14:23:30

标签: jquery ajax

对于下面的ajax请求,我看到多个请求发送到服务器。我该如何防止它。

        $('#winnerEditModal').modal().promise().done(function () {
                $('#updateWinnerBtn').click(function () {
                    debugger
                    var currentModal = $(this).closest('.modal');
                    var postBody = {};
                    var inputIds=currentModal.find('input').map(function(){return $(this).attr('id')});
                    var inputVals=currentModal.find('input').map(function(){return $(this).val()});
                    var id = currentModal.attr('winnerId');
                    postBody.id = id;
                    _.each(inputIds, function (v, k) {
                        var key = inputIds[k];
                        var val = inputVals[k];
                        postBody[key] = val;
                    });

                    editWinner(postBody).done(function (response) {
                        console.log(response)
                        if(response){
                            $table.bootstrapTable('refresh');
                            toastr.success('Winner is updated successfully');
                        }else{
                            toastr.error('Winner is not updated successfully. Check info again!!');
                        }
                    })
                });
            });

这是调用ajax帖子的功能。是什么导致了这种行为,我该如何防止它

var editWinner = function (postBody) {
    return $.post({
        url: getCookie('digrectargetDomain')  + 'api/winner/edit',
       // type: 'POST',
        contentType : 'application/json',
        data : JSON.stringify(postBody),
        beforeSend: function (xhr) {
            xhr.setRequestHeader('Authorization', getCookie('digrectoken'));
        }
    });
}

1 个答案:

答案 0 :(得分:1)

问题是每次模型承诺解析时都绑定一个单击处理程序(参见代码的前两行)。

只需从done回调中获取点击处理程序:

var isResolved = false;
$('#updateWinnerBtn').click(function () {
    if (!resolved) return; // <-- handle click only when resolved
    debugger
    // rest of the click handler ...
    // ...
});

$('#winnerEditModal').modal().promise().done(function () {
    isResolved = true; // allow clicks to be handled
});