程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了jQuery 中止 ajax 调用无法正常工作大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决jQuery 中止 ajax 调用无法正常工作?

开发过程中遇到jQuery 中止 ajax 调用无法正常工作的问题如何解决?下面主要结合日常开发的经验,给出你关于jQuery 中止 ajax 调用无法正常工作的解决方法建议,希望对你解决jQuery 中止 ajax 调用无法正常工作有所启发或帮助;

如果我单击一个按钮,我将尝试中止所有挂起的 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();
@H_403_5@

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

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

问题

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

有人能解释一下我在这里做错了什么吗?

谢谢

解决方法

是因您使用了 splice,所以在循环时索引发生了变化。例如:当 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");
}

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

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

大佬总结

以上是大佬教程为你收集整理的jQuery 中止 ajax 调用无法正常工作全部内容,希望文章能够帮你解决jQuery 中止 ajax 调用无法正常工作所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。