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 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系