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

中止所有异步请求

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

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

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵