How do you terminate JQUERY's $.AJAX request

  • 2021-01-03 20:50:01
  • OfStack

Recently, there were two problems with users clicking on ajax requests frequently:

1. If you click on five ajax requests in a row, the first four are actually invalid. Save resources by ending as soon as possible.

2. The more serious problem is that the last request sent is not necessarily the last response, which may cause confusion. A queue is also required to maintain the sent requests and responses.

I had already worked out how the queue would be implemented, and found that jQuery went directly to the abort method, which didn't require a very complicated implementation because there were other things to do.

It is very convenient to send ajax requests using jquery, $.get, $.post, $.ajax, etc., but sometimes we need to abort ajax requests.

For example, when chatting with comet, after sending a request, the server usually waits a few seconds before refreshing the link and returning the data. Suppose the server refreshes the link every 30 seconds. What if we want to stop the ajax request at 10 seconds?

Code first, explain later


var ajaxGet = $.get( " comet_server.php " ,{id:1},function(data){
 ... .//1 Some operation 
});
ajaxGet.abort();

The above code is based on two points:

1. $.get returns data type XMLHttpRequest, please refer to the manual. ($.post, $.ajax, $.getJSON, $.getScript)

2. The XMLHttpRequest object has the abort() method

Note: After abort(), ajax requests stop immediately, but the following function() is executed anyway. If you want to avoid performing any of these operations, you can add judgment at the beginning of function()


var ajaxGet = $.get( " comet_server.php " ,{id:1},function(data){
if(data.length == 0) return true;
 ... .//1 Some operation 
});
ajaxGet.abort();

Terminate ajax request:


var request = $.get( " ajax.aspx " ,{id:1},function(data){
  //do something
});
// Abort request action .
request.abort();

Prevent duplicate requests:


var request;
if(request != null)
  request.abort();
request = $.get( " ajax.aspx " ,{id:1},function(){
  //do something
});
ajax & setTimeout implementation  secondTry  Waiting for the 1 Seconds later will firstTry the ajax Termination: 
var firstTry = $.ajax(
 //do something
 );
var secondTry = setTimeout(function(){alert( ' ok');firstTry.abort()},1000);


Related articles: