2016-06-11 156 views
1

我想根據變量立即拒絕所有的AJAX請求。我明白如何掛接XMLHttpRequest,但不知道如何拒絕它。拒絕所有的AJAX請求

(function(open) { 
      XMLHttpRequest.prototype.open = function(method, url, async, user, pass) { 
       this.addEventListener("readystatechange", function() { 
        if(this.readyState === 1){ 
         // stop all ajax attempts if we're disconnected 
         if(!self.isConnected){ 
          console.log('rejecting') 
          // reject here 
          this.abort(); // ??? 
         } 
        } 
       }, false); 
       open.call(this, method, url, async, user, pass); 
      }; 
     })(XMLHttpRequest.prototype.open); 

此外,我想知道,如果內 this.readyState === 0調用這個類似於稱之爲「當請求第一次啓動」

回答

0

您可以使用終止函數終止Ajax請求,先保存您的請求一些變量並調用它

$(document).ready(
    var xhr; 

    var fn = function(){ 
     if(xhr && xhr.readyState != 4){ 
      xhr.abort(); 
     } 
     xhr = $.ajax({ 
      url: 'ajax/progress.ftl', 
      success: function(data) { 
       //do something 
      } 
     }); 
    }; 

    var interval = setInterval(fn, 500); 
); 

中止有創建AJAX池設置,我不推薦,fiddle這裏

0的另一種方法
$.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); 
     } 
    } 
}); 
+0

爲什麼downvote ???? –

+0

我對所有請求感興趣 – Tester232323

+0

@ Tester232323:那麼你需要保留你的所有請求在一些數組中,然後你可以調用它們中止......你需要維護一個請求變量 –

0

我只是簡單地添加

this.abort()

,這似乎在需要時立即中止所有請求。