Stop all active ajax requests in jQuery

前端 未结 16 1103
自闭症患者
自闭症患者 2020-11-22 13:51

I have a problem, when submitting a form all active ajax request fail, and that triggers error event.

How to stop all active ajax requests in jQuery without trigerri

16条回答
  •  情书的邮戳
    2020-11-22 14:26

    Using ajaxSetup is not correct, as is noted on its doc page. It only sets up defaults, and if some requests override them there will be a mess.

    I am way late to the party, but just for future reference if someone is looking for a solution to the same problem, here is my go at it, inspired by and largely identical to the previous answers, but more complete

    // 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);
    

提交回复
热议问题