【问题标题】:jQuery aborting ajax calls not working properlyjQuery 中止 ajax 调用无法正常工作
【发布时间】:2021-06-13 06:00:03
【问题描述】:

如果我单击一个按钮,我会尝试中止所有待处理的 ajax 调用。我有以下 javascript 代码。

var MyApp = function() {
    this.xhrPool = [];
}

MyApp.constructor = MyApp;

MyApp.prototype.fetchDataFromApi = function() {
    var rows = $("tr.data-row");

    var _obj = this;

    rows.each(function(index, rowData){
        $.ajax({
            type: "GET",
            url: "http://wwww.example.com/somepage/",
            dataType: "json",
            beforeSend: function(jqXHR){
                _obj.xhrPool.push(jqXHR);
            },
            success: function(response){
                //do something here on successful call
            },
            complete: function(jqXHR){
                var i = _obj.xhrPool.indexOf(jqXHR);
                if(i > -1) _obj.xhrPool.splice(i,1);
            },
            error: function(request, status, error){
                //do something else here on ajax error
            }
        });

    });
}

MyApp.prototype.AbortAllAjaxCall = function(){
    if(this.xhrPool.length > 0){
        var xhrPoolLength = this.xhrPool.length;

        for(x in this.xhrPool){
            this.xhrPool[x].abort();
            this.xhrPool.splice(x,1);
            console.warn("Aborted "+x+" ajax calls");
        }

        alert(this.xhrPool.length+ " of "+xhrPoolLength+" calls aborted");
    }
}

var app = new MyApp();

一次总是有 40 个调用。我已经限制了 ajax 调用,以便在几分钟内没有任何调用响应任何内容。即所有 40 个呼叫的状态保持等待几分钟。

我有一个按钮,点击调用app.AbortAllAjaxCall()app.AbortAllAjaxCall() 方法在循环中中止 ajax 调用,最后提醒中止调用的长度为总 ajax 调用的长度。

问题

但是,问题在于,通过单击该按钮,所有 ajax 调用都应该被中止,但事实并非如此。我必须点击按钮 3-4 次才能中止所有 ajax 调用。

谁能解释我在这里做错了什么?

谢谢

【问题讨论】:

    标签: javascript jquery ajax


    【解决方案1】:

    这是因为你使用了拼接,所以在循环时索引发生了变化。例如:当x 为 0 时,您中止第一个 ajax 并将其从数组中删除,因此索引为 1 的元素将成为第一个元素,并且当x 变为 1 时不会中止。要解决此问题,您可以从数组结束:

    for (let x = this.xhrPool.length - 1; x >= 0; x--){
      this.xhrPool[x].abort();
      this.xhrPool.splice(x,1);
      console.warn("Aborted "+x+" ajax calls");
    }
    

    或者在不使用拼接的情况下中止所有 ajax 后将 xhrPool 设置为空数组:

    for(x in this.xhrPool){
      this.xhrPool[x].abort();
      console.warn("Aborted "+x+" ajax calls");
    }
    this.xhrPool = [];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-17
      • 1970-01-01
      • 2014-02-11
      • 1970-01-01
      • 2014-01-11
      相关资源
      最近更新 更多