繁体   English   中英

jQuery 中止 ajax 调用无法正常工作

[英]jQuery aborting ajax calls not working properly

如果单击按钮,我将尝试中止所有待处理的 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 调用。

任何人都可以阐明我在这里做错了什么吗?

谢谢

这是因为您使用了拼接,所以索引在循环时发生了变化。 例如:当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 = [];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM