douxie0824 2016-02-04 05:22
浏览 338
已采纳

中止所有异步请求

In my page, I call 15 ajax request. Also I have a button which cancels all the pending ajax requests. As per documentation, abort() terminates the request if it has already been sent.

Now when I check my console, even after I click cancel button, I get some replies from ajax script (I guess those were already sent by the time I clicked that button). So how can I make sure no reply should come once I press cancel button?

You can check the script here (couldn't use jsfiddle as not sure how to make ajax request).

JS Code

var xhrPool = [];

$(window).load(function(){
        callAjax1();
});

$.ajaxSetup({
    beforeSend: function(jqXHR) {
        xhrPool.push(jqXHR);
    },
    complete: function(jqXHR) {
        var index = xhrPool.indexOf(jqXHR);
        if (index > -1) {
            xhrPool.splice(index, 1);
        }
    }
});

var abortAjax = function () {
    $.each(xhrPool, function(idx, jqXHR) {
        if(jqXHR && jqXHR .readystate != 4){
            jqXHR.abort();
        }
    });
    console.log("All pending cancelled"); // Should not have any ajax return after this point
    $.xhrPool = [];
};

$("#cancel-button").click(function (){
        abortAjax();
});


function callAjax2(ajaxcallid){
    console.log("Initiate ajax call " + ajaxcallid); // Should not have any ajax return after this point
    $.ajax({
        method: "POST",
        url: "test.php"
    })
    .done(function( msg ) {
        console.log(msg + ajaxcallid); // msg = "Ajax return for "
    })
    .fail(function( jqXHR, textStatus, errorThrown) {
        console.log(errorThrown);
    });
}

function callAjax1(){
    $.ajax({
        method: "POST",
        url: "test.php"
    })
    .done(function( msg ) {
        for(var i = 0; i < 15; i++){
            callAjax2(i);
        }
    })
    .fail(function( jqXHR, textStatus, errorThrown) {
        console.log(errorThrown);
    });
}

Console Output: enter image description here

  • 写回答

1条回答 默认 最新

  • doushi8187 2016-02-04 05:54
    关注

    try this

    $.each(xhrPool.slice(), function(idx, jqXHR) {
    

    I think while you are aborting, some are returning, so the array gets messed up

    this way you are working with a snapshot of the array

    though, one or two may still sneak through due to timing of course

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型