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 R语言单细胞测序 对seurat对象进行标准化时出现问题
  • ¥15 Anaconda navigator updateor一直更新
  • ¥15 请问如何在matlab里使用raven工具?
  • ¥100 关于ios手游充值到一定金额,再点充值提示公众号的问题。
  • ¥15 求一个stm32串口控制程序
  • ¥20 Windows 驱动开发版本疑问相关
  • ¥15 MAC 未能打开磁盘映像
  • ¥15 fastcap使用,二维导体输入问题
  • ¥15 hosts修改后不能访问
  • ¥15 关于化学反应速率C++编译问题/FLUENT