代码之家  ›  专栏  ›  技术社区  ›  Robert W

全局中止所有jquery ajax请求

  •  19
  • Robert W  · 技术社区  · 16 年前

    是否有一种方法可以在没有请求对象句柄的情况下全局中止所有Ajax请求?

    我问的原因是我们有一个非常复杂的应用程序,我们在后台使用setTimeout()运行许多不同的Ajax请求。如果用户单击某个按钮,我们需要停止所有正在进行的请求。

    4 回复  |  直到 9 年前
        1
  •  13
  •   Sarfraz    16 年前

    你需要打电话 abort() 方法:

    var request = $.ajax({
        type: 'POST',
        url: 'someurl',
        success: function(result){..........}
    });
    

    之后,您可以中止请求:

    request.abort();
    

    这样,您需要为Ajax请求创建一个变量,然后可以使用 abort 方法随时终止请求。

    还可以看看:

        2
  •  7
  •   7wp    16 年前

    如果不跟踪所有活动的Ajax请求的句柄,则无法中止这些请求。

    但是如果您正在跟踪它,那么是的,您可以通过循环遍历处理程序并调用 .abort() 在每一个。

        3
  •  4
  •   Peter Mortensen Pieter Jan Bonestroo    10 年前

    您可以使用此脚本:

    // $.xhrPool and $.ajaxSetup are the solution
    $.xhrPool = [];
    $.xhrPool.abortAll = function() {
        $(this).each(function(idx, jqXHR) {
            jqXHR.abort();
        });
        $.xhrPool = [];
    };
    
    $.ajaxSetup({
        beforeSend: function(jqXHR) {
            $.xhrPool.push(jqXHR);
        },
        complete: function(jqXHR) {
            var index = $.xhrPool.indexOf(jqXHR);
            if (index > -1) {
                $.xhrPool.splice(index, 1);
            }
        }
    });
    

    检查结果 http://jsfiddle.net/s4pbn/3/ .

        4
  •  3
  •   Community Mohan Dere    9 年前

    对一个相关问题的回答对我有帮助:

    https://stackoverflow.com/a/10701856/5114

    注意@grr所说的第一行:“使用AjaxSetup不正确”

    如果您想自己调用它而不是使用它,您可以调整他的答案,将您自己的函数添加到窗口中。 window.onbeforeunload 就像他们那样。

    // Most of this is copied from @grr verbatim:
    (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});
      });
      // I changed the name of the abort function here:
      window.abortAllMyAjaxRequests = function() {
        $.each(xhrPool, function(idx, jqXHR) {
          jqXHR.abort();
        });
      };
    })(jQuery);
    

    然后你可以打电话 window.abortAllMyAjaxRequests(); 全部中止。确保添加 .fail(jqXHRFailCallback) 到您的Ajax请求。回调将得到“abort”作为 textStatus 所以你知道发生了什么:

    function jqXHRFailCallback(jqXHR, textStatus){
      // textStatus === 'abort'
    }