jQuery abandon all outstanding AJAX requests
Is there any easy way to abandon all outstanding jQuery AJAX开发者_如何学C requests? My application is capable of pulling off a lot of simultaneous requests, so race becomes problematic. I've put in hackish solutions (namely, putting in a flag that is checked upon request completion), but it would be much nicer to get a global stop all outstanding requests function.
Assign every ajax request as an element of an array:
var requests = [];
requests.push($.ajax({
type: 'POST',
url: '...',
success: successfunc
});
);
And to kill:
$.each(requests, function(i, v) {
v.abort();
});
as the others have said, use the .abort() method. However, this ONLY works on calls within the same domain. once you enter into cross-site calls (with jsonp), then the .abort() method is delegated to null, so wont actually fire/work.
worth noting as this caused me endless debugging time many a small moon ago :)
jim
Based on Ken Redler's solution, I put this in 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 put in the snippet with new_request_list
just to keep the global variable from getting crowded with completed XHR objects.
XMLHttpRequest has an abort() function. $.ajax lets you get your hands on the xhr object. keep a record of all outstanding xhr's and go xhr.abort()
for any you want to terminate.
I would say store all ajax requests in an array. When you need to kill then just loop through all values in array and call abort(). When a request is completed or aborted just pop from the array.
I found the following on jsfiddle. It is mostly the same as above, except it will remove each request once they are complete. The solutions above just keep adding to the array. So over time, it could get huge if you are making a lot of ajax calls. You call $.xhrPool.abortAll();
when you want to abort 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);
}
}
});
精彩评论