Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
停止jQuery中所有活动的ajax请求_Jquery_Ajax - Fatal编程技术网

停止jQuery中所有活动的ajax请求

停止jQuery中所有活动的ajax请求,jquery,ajax,Jquery,Ajax,我有一个问题,当提交表单时,所有活动的ajax请求都失败了,这会触发错误事件 如何在不触发错误事件的情况下停止jQuery中所有活动的ajax请求?每次创建ajax请求时,都可以使用变量来存储它: var request = $.ajax({ type: 'POST', url: 'someurl', success: function(result){} }); 然后您可以中止请求: request.abort(); 您可以使用一个数组来跟踪所有挂起的ajax请求,

我有一个问题,当提交表单时,所有活动的ajax请求都失败了,这会触发错误事件


如何在不触发错误事件的情况下停止jQuery中所有活动的ajax请求?

每次创建ajax请求时,都可以使用变量来存储它:

var request = $.ajax({
    type: 'POST',
    url: 'someurl',
    success: function(result){}
});
然后您可以中止请求:

request.abort();

您可以使用一个数组来跟踪所有挂起的ajax请求,并在必要时中止它们。

以下是我目前用来实现这一点的方法

$.xhrPool = [];
$.xhrPool.abortAll = function() {
  _.each(this, function(jqXHR) {
    jqXHR.abort();
  });
};
$.ajaxSetup({
  beforeSend: function(jqXHR) {
    $.xhrPool.push(jqXHR);
  }
});

注意:551;。每个underline.js都存在,但显然不是必需的。我只是很懒,不想把它改成$.each()。8P

我对andy的代码有一些问题,但它给了我一些很棒的想法。第一个问题是,我们应该弹出任何成功完成的jqXHR对象。我还必须修改abortAll函数。这是我最后的工作代码:

$.xhrPool = [];
$.xhrPool.abortAll = function() {
            $(this).each(function(idx, jqXHR) {
                        jqXHR.abort();
                        });
};
$.ajaxSetup({
    beforeSend: function(jqXHR) {
            $.xhrPool.push(jqXHR);
            }
});
$(document).ajaxComplete(function() {
            $.xhrPool.pop();
            });

我不喜欢那种做事的方式。无论我如何配置.ajaxSetup,它都无法工作。

下面的代码段允许您维护请求列表(池),并在需要时全部中止它们。最好在进行任何其他AJAX调用之前,将其放入html的

<script type="text/javascript">
    $(function() {
        $.xhrPool = [];
        $.xhrPool.abortAll = function() {
            $(this).each(function(i, jqXHR) {   //  cycle through list of recorded connection
                jqXHR.abort();  //  aborts connection
                $.xhrPool.splice(i, 1); //  removes from list by index
            });
        }
        $.ajaxSetup({
            beforeSend: function(jqXHR) { $.xhrPool.push(jqXHR); }, //  annd connection to list
            complete: function(jqXHR) {
                var i = $.xhrPool.indexOf(jqXHR);   //  get index for current connection completed
                if (i > -1) $.xhrPool.splice(i, 1); //  removes from list by index
            }
        });
    })
</script>

$(函数(){
$.xhrPool=[];
$.xhrPool.abortAll=函数(){
$(this).each(函数(i,jqXHR){//循环遍历记录的连接列表
jqXHR.abort();//中止连接
$.xhrPool.splice(i,1);//按索引从列表中删除
});
}
$.ajaxSetup({
beforeSend:function(jqXHR){$.xhrPool.push(jqXHR);},//添加到列表的连接
完成:函数(jqXHR){
var i=$.xhrPool.indexOf(jqXHR);//获取当前连接的索引已完成
if(i>-1)$.xhrPool.splice(i,1);//按索引从列表中删除
}
});
})
使用,如其文档页所述。它只设置默认值,如果一些请求覆盖了它们,就会出现混乱

我参加聚会已经晚了很多,但如果有人在寻找同一问题的解决方案,我只是为了将来的参考,以下是我的尝试,灵感来源于前面的答案,基本上与前面的答案相同,但更完整

// Automatically cancel unfinished ajax requests 
// when the user navigates elsewhere.
(function($) {
  var xhrPool = [];
  $(document).ajaxSend(function(e, jqXHR, options){
    xhrPool.push(jqXHR);
  });
  $(document).ajaxComplete(function(e, jqXHR, options) {
    xhrPool = $.grep(xhrPool, function(x){return x!=jqXHR});
  });
  var abort = function() {
    $.each(xhrPool, function(idx, jqXHR) {
      jqXHR.abort();
    });
  };

  var oldbeforeunload = window.onbeforeunload;
  window.onbeforeunload = function() {
    var r = oldbeforeunload ? oldbeforeunload() : undefined;
    if (r == undefined) {
      // only cancel requests if there is no prompt to stay on the page
      // if there is a prompt, it will likely give the requests enough time to finish
      abort();
    }
    return r;
  }
})(jQuery);

给每个xhr请求一个唯一的id,并在发送之前将对象引用存储在对象中。 在xhr请求完成后删除引用

要随时取消所有请求,请执行以下操作:

$.ajaxQ.abortAll();
返回已取消请求的唯一ID。仅用于测试目的

工作职能:

$.ajaxQ = (function(){
  var id = 0, Q = {};

  $(document).ajaxSend(function(e, jqx){
    jqx._id = ++id;
    Q[jqx._id] = jqx;
  });
  $(document).ajaxComplete(function(e, jqx){
    delete Q[jqx._id];
  });

  return {
    abortAll: function(){
      var r = [];
      $.each(Q, function(i, jqx){
        r.push(jqx._id);
        jqx.abort();
      });
      return r;
    }
  };

})();

返回一个具有单个函数的对象,该对象可以在需要时用于添加更多功能。

同样重要:假设您想注销,并且正在使用计时器生成新请求:因为会话数据会随着每个新的引导更新(也许您可以说我是Drupal,但这可能是任何使用会话的站点)。。。我必须通过搜索和替换来检查我的所有脚本,因为我有很多东西在不同的情况下运行:顶部是全局变量:

var ajReq = [];
var canAj = true;
function abort_all(){
 for(x in ajReq){
    ajReq[x].abort();
    ajReq.splice(x, 1)
 }
 canAj = false;
}
function rmvReq(ranNum){
 var temp = [];
 var i = 0;
 for(x in ajReq){
    if(x == ranNum){
     ajReq[x].abort();
     ajReq.splice(x, 1);
    }
    i++;
 }
}
function randReqIndx(){
 if(!canAj){ return 0; }
 return Math.random()*1000;
}
function getReqIndx(){
 var ranNum;
 if(ajReq.length){
    while(!ranNum){
     ranNum = randReqIndx();
     for(x in ajReq){
    if(x===ranNum){
     ranNum = null;
    }
     }
    }
    return ranMum;
 }
 return randReqIndx();
}
$(document).ready(function(){
 $("a").each(function(){
    if($(this).attr('href').indexOf('/logout')!=-1){          
     $(this).click(function(){
    abort_all();                 
     });
    }
 })
});
// Then in all of my scripts I wrapped my ajax calls... If anyone has a suggestion for a 
    // global way to do this, please post
var reqIndx = getReqIndx();
if(reqIndx!=0){
ajReq[reqIndx] = $.post(ajax, { 'action': 'update_quantities', iids:iidstr, qtys:qtystr },  
function(data){
 //..do stuff
 rmvReq(reqIndx);
 },'json');
}

我已经更新了代码,使其适合我

$.xhrPool = [];
$.xhrPool.abortAll = function() {
    $(this).each(function(idx, jqXHR) {
        jqXHR.abort();
    });
    $(this).each(function(idx, jqXHR) {
        var index = $.inArray(jqXHR, $.xhrPool);
        if (index > -1) {
            $.xhrPool.splice(index, 1);
        }
    });
};

$.ajaxSetup({
    beforeSend: function(jqXHR) {
        $.xhrPool.push(jqXHR);
    },
    complete: function(jqXHR) {
        var index = $.inArray(jqXHR, $.xhrPool);
        if (index > -1) {
            $.xhrPool.splice(index, 1);
        }
    }
});

下面介绍了如何在任何单击时将其连接起来(如果您的页面正在放置许多AJAX调用,并且您正试图导航离开,那么这将非常有用)


我扩展了上面的mkmurray和SpYk3HH答案,以便xhrPool.abortAll可以中止给定url的所有挂起请求

$.xhrPool = [];
$.xhrPool.abortAll = function(url) {
    $(this).each(function(i, jqXHR) { //  cycle through list of recorded connection
        console.log('xhrPool.abortAll ' + jqXHR.requestURL);
        if (!url || url === jqXHR.requestURL) {
            jqXHR.abort(); //  aborts connection
            $.xhrPool.splice(i, 1); //  removes from list by index
        }
    });
};
$.ajaxSetup({
    beforeSend: function(jqXHR) {
        $.xhrPool.push(jqXHR); //  add connection to list
    },
    complete: function(jqXHR) {
        var i = $.xhrPool.indexOf(jqXHR); //  get index for current connection completed
        if (i > -1) $.xhrPool.splice(i, 1); //  removes from list by index
    }
});
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
    console.log('ajaxPrefilter ' + options.url);
    jqXHR.requestURL = options.url;
});

用法相同,只是abortAll现在可以选择接受url作为参数,并且只取消对该url的挂起调用。针对
xhrPool
数组提供
abort
remove
方法,并且不容易出现
ajaxSetup
覆盖问题

/**
 * Ajax Request Pool
 * 
 * @author Oliver Nassar <onassar@gmail.com>
 * @see    http://stackoverflow.com/questions/1802936/stop-all-active-ajax-requests-in-jquery
 */
jQuery.xhrPool = [];

/**
 * jQuery.xhrPool.abortAll
 * 
 * Retrieves all the outbound requests from the array (since the array is going
 * to be modified as requests are aborted), and then loops over each of them to
 * perform the abortion. Doing so will trigger the ajaxComplete event against
 * the document, which will remove the request from the pool-array.
 * 
 * @access public
 * @return void
 */
jQuery.xhrPool.abortAll = function() {
    var requests = [];
    for (var index in this) {
        if (isFinite(index) === true) {
            requests.push(this[index]);
        }
    }
    for (index in requests) {
        requests[index].abort();
    }
};

/**
 * jQuery.xhrPool.remove
 * 
 * Loops over the requests, removes it once (and if) found, and then breaks out
 * of the loop (since nothing else to do).
 * 
 * @access public
 * @param  Object jqXHR
 * @return void
 */
jQuery.xhrPool.remove = function(jqXHR) {
    for (var index in this) {
        if (this[index] === jqXHR) {
            jQuery.xhrPool.splice(index, 1);
            break;
        }
    }
};

/**
 * Below events are attached to the document rather than defined the ajaxSetup
 * to prevent possibly being overridden elsewhere (presumably by accident).
 */
$(document).ajaxSend(function(event, jqXHR, options) {
    jQuery.xhrPool.push(jqXHR);
});
$(document).ajaxComplete(function(event, jqXHR, options) {
    jQuery.xhrPool.remove(jqXHR);
});
/**
*Ajax请求池
* 
*@作者奥利弗·纳斯尔
*@见http://stackoverflow.com/questions/1802936/stop-all-active-ajax-requests-in-jquery
*/
jQuery.xhrPool=[];
/**
*jQuery.xhrPool.abortAll
* 
*从阵列检索所有出站请求(因为阵列正在运行)
*在请求中止时进行修改),然后在每个请求上循环以
*做流产手术。这样做将触发针对的ajaxComplete事件
*文档,它将从池数组中删除请求。
* 
*@access-public
*@返回无效
*/
jQuery.xhrPool.abortAll=函数(){
var请求=[];
for(本节中的var索引){
if(isFinite(index)==true){
请求。推送(此[索引]);
}
}
for(请求中的索引){
请求[索引]。中止();
}
};
/**
*jQuery.xhrPool.remove
* 
*在请求上循环,一旦(如果)找到它就将其删除,然后中断
*循环的一部分(因为没有其他事情要做)。
* 
*@access-public
*@param对象jqXHR
*@返回无效
*/
jQuery.xhrPool.remove=函数(jqXHR){
for(本节中的var索引){
if(此[索引]==jqXHR){
jQuery.xhrPool.splice(索引,1);
打破
}
}
};
/**
*以下事件附加到文档中,而不是在ajaxSetup中定义
*防止可能在其他地方被覆盖(可能是意外)。
*/
$(文档).ajaxSend(函数(事件、jqXHR、选项){
jQuery.xhrPool.push(jqXHR);
});
$(文档).ajaxComplete(函数(事件、jqXHR、选项){
jQuery.xhrPool.remove(jqXHR);
});

最好使用独立代码

var xhrQueue = []; 

$(document).ajaxSend(function(event,jqxhr,settings){
    xhrQueue.push(jqxhr); //alert(settings.url);
});

$(document).ajaxComplete(function(event,jqxhr,settings){
    var i;   
    if((i=$.inArray(jqxhr,xhrQueue)) > -1){
        xhrQueue.splice(i,1); //alert("C:"+settings.url);
    }
});

ajaxAbort = function (){  //alert("abortStart");
    var i=0;
    while(xhrQueue.length){ 
        xhrQueue[i++] .abort(); //alert(i+":"+xhrQueue[i++]);
    }
};

创建一个包含所有ajax请求的池并中止它们

var xhrQueue = []; 

$(document).ajaxSend(function(event,jqxhr,settings){
    xhrQueue.push(jqxhr); //alert(settings.url);
});

$(document).ajaxComplete(function(event,jqxhr,settings){
    var i;   
    if((i=$.inArray(jqxhr,xhrQueue)) > -1){
        xhrQueue.splice(i,1); //alert("C:"+settings.url);
    }
});

ajaxAbort = function (){  //alert("abortStart");
    var i=0;
    while(xhrQueue.length){ 
        xhrQueue[i++] .abort(); //alert(i+":"+xhrQueue[i++]);
    }
};

我发现它对于多个请求来说太容易了

步骤1:在页面顶部定义一个变量:

  xhrPool = []; // no need to use **var**
步骤2:在发送所有ajax请求之前设置:

  $.ajax({
   ...
   beforeSend: function (jqXHR, settings) {
        xhrPool.push(jqXHR);
    },
    ...
第三步:在需要时使用它:

   $.each(xhrPool, function(idx, jqXHR) {
          jqXHR.abort();
    });
每当您想要中止所有ajax请求时,您只需要调用这一行

Request.AbortAll()

我使用一个虚拟解决方案中止所有ajax请求。此解决方案是重新加载整个页面。如果您不想为每个ajax请求分配一个ID,并且如果您在fo中发出ajax请求,那么这个解决方案是很好的
var Request = {
    List: [],
    AbortAll: function () {
        var _self = this;
        $.each(_self.List, (i, v) => {
            v.abort();
        });
    }
}
var settings = {
    "url": "http://localhost",
    success: function (resp) {
        console.log(resp)
    }
}

Request.List.push($.ajax(settings));
Request.AbortAll()
location.reload();