JQuery rejects all outstanding AJAX requests

Is there an easy way to refuse all outstanding jQuery AJAX queries? My application is able to remove many simultaneous requests, so the race becomes problematic. I turned on hacking solutions (namely, set a flag that is checked at the end of the request), but it would be much better to get a global stop of all outstanding request functions.

+6
jquery ajax
source share
6 answers

Assign each ajax request as an array element:

var requests = []; requests.push($.ajax({ type: 'POST', url: '...', success: successfunc }); ); 

And kill:

 $.each(requests, function(i, v) { v.abort(); }); 
+11
source share

as others have said, use the .abort () method. However, this ONLY works with calls within the same domain. as soon as you enter cross-site calls (with jsonp), then the .abort () method is delegated to null, so it usually doesn't work / work.

It is worth noting, because it caused me an endless time of debugging a lot of the little moon back :)

Jim

+3
source share

Based on Ken Redler's solution, I put this on my initialization:

 window.requests = [] $.ajaxSetup({ beforeSend: function(xhr){ var new_request_list = [xhr] $.each(window.requests, function(k,v){ if(v.readyState != 4) new_request_list.push(v) }) window.requests = new_request_list } }) 

I included the new_request_list only so that the global variable is not populated with populated XHR objects.

+3
source share

XMLHttpRequest has an abort () function. $ .ajax allows you to access the xhr object. keep a record of all the outstanding xhr and go xhr.abort() for whatever you want to complete.

+2
source share

I would say to store all ajax requests in an array. When you need to kill, just swipe all the values ​​in the array and call abort (). When the request is completed or aborted, just pop out of the array.

+1
source share

I found the following in jsfiddle . It is basically the same as above, except that it will delete every request after its completion. The above solutions just add to the array. So over time, this can become huge if you make a lot of ajax calls. You call $.xhrPool.abortAll(); when you want to cancel all outstanding requests.

 // $.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); } } }); 
+1
source share

All Articles