Recently encountered, if users frequently click on AJAX requests, there are two problems:
1, if a continuous click of 5 AJAX requests, the first 4 is actually invalid, save resources as early as the end.
2, the more serious problem is: The last request sent, the response may not be the last one, can cause confusion. A queue is also required to maintain the sent requests and responses.
I have actually designed the implementation of the queue, and later found that jquery directly through the Abort method, so it does not need so complex implementation, after all, there are other things to be done.
It's really convenient to send Ajax requests in jquery, $.get, $.post, $.ajax, and so on, but sometimes we need to abort the AJAX request halfway.
For example, when using Comet to do a chat, after sending a request, the server usually refreshes the link and returns data after a few 10 seconds. Suppose the service end is a 30 second refresh link, what if we want to stop this Ajax request in 10 seconds?
Code first, then explain later.
var ajaxget = $.get ("comet_server.php", {id:1},function (data) {
...//some operations
});
Ajaxget.abort ();
The above code is in the two knowledge points:
1. The data type returned by $.get is XMLHttpRequest, please refer to the manual. ($.post, $.ajax, $.getjson, $.getscript)
2. XMLHttpRequest object has abort () method
Note: After abort (), the AJAX request stops immediately, but the following function () is executed. If you want to avoid doing this, you can add a judgment at the start of the function ()
var ajaxget = $.get ("comet_server.php", {id:1},function (data) {
if (data.length = 0) return true;
...//Some Operations
});
Ajaxget.abort ();
To terminate an AJAX request:
var request = $.get ("ajax.aspx", {id:1},function (data) {
//do something
});
Terminates the 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 after waiting one second to terminate firsttry Ajax:
var firsttry = $.ajax (//do something
);
var secondtry = settimeout (function () {alert (' OK '); Firsttry.abort ()},1000);