Home > Article > Web Front-end > Teach you how to terminate JQUERY's $.AJAX request_jquery
I recently encountered that if users frequently click on ajax requests, there are two problems:
1. If you click 5 ajax requests in a row, the first 4 are actually invalid. End it as soon as possible to save resources.
2. The more serious problem is: the response to the last request sent may not be the last one, which may cause confusion. A queue is also needed to maintain sent requests and responses.
I have actually designed the implementation of the queue, and later found that jQuery directly uses the abort method, so there is no need for such a complicated implementation. After all, there are other things waiting to be completed.
It is really convenient to use jquery to send ajax requests, $.get, $.post, $.ajax, etc., but sometimes we need to terminate the ajax request midway.
For example, when using comet for chatting, after sending a request, the server usually refreshes the link and returns data after dozens of seconds. Assume that the server refreshes the link every 30 seconds. What if we want to stop the ajax request at 10 seconds?
Let’s start with the code and explain later
var ajaxGet = $.get(“comet_server.php”,{id:1},function(data){ ….//一些操作 }); ajaxGet.abort();
The above code consists of two knowledge points:
1. The data type returned by $.get is XMLHttpRequest, please refer to the manual. (Same goes for $.post, $.ajax, $.getJSON, $.getScript)
2. XMLHttpRequest object has abort() method
Note: After abort(), the ajax request stops immediately, but the subsequent function() will still be executed. If you want to avoid performing the operations, you can add a judgment at the beginning of function()
var ajaxGet = $.get(“comet_server.php”,{id:1},function(data){ if(data.length == 0) return true; ….//一些操作 }); ajaxGet.abort();
Terminate ajax request:
var request = $.get(“ajax.aspx”,{id:1},function(data){ //do something }); //终止请求动作. request.abort();
Prevent duplicate requests:
var request; if(request != null) request.abort(); request = $.get(“ajax.aspx”,{id:1},function(){ //do something }); ajax & setTimeout实现 secondTry 在等待一秒之后将firstTry的ajax终止: var firstTry = $.ajax( //do something ); var secondTry = setTimeout(function(){alert(‘ok');firstTry.abort()},1000);