There is nothing complicated, that is, using an array object as a queue to maintain the order of ajax requests. The following code is provided:
Copy codeThe Code is as follows:
; (Function ($ ){
$. AjaxQueue = {
// Manage the queue of ajax requests
Requests: new Array (),
// Add the ajax request to the queue
Offer: function (options ){
Var _ self = this,
// "Hijack" the complete and beforeSend methods and add them to the queue processing method poll
XhrOptions = $. extend ({}, options ,{
// If the request is complete, send the next request
Complete: function (jqXHR, textStatus ){
If (options. complete)
Options. complete. call (this, jqXHR, textStatus );
_ Self. poll ();
},
// If the request is canceled, send the next request
BeforeSend: function (jqXHR, settings ){
If (options. beforeSend)
Var ret = options. beforeSend. call (this, jqXHR, settings );
If (ret = false ){
_ Self. poll ();
Return ret;
}
}
});
This. requests. push (xhrOptions );
If (this. requests. length = 1 ){
$. Ajax (xhrOptions );
}
},
// Send ajax requests in FIFO mode
Poll: function (){
If (this. isEmpty ()){
Return null;
}
Var processedRequest = this. requests. shift ();
Var nextRequest = this. peek ();
If (nextRequest! = Null ){
$. Ajax (nextRequest );
}
Return processedRequest;
},
// Return the ajax request in the queue Header
Peek: function (){
If (this. isEmpty ()){
Return null;
}
Var nextRequest = this. requests [0];
Return nextRequest;
},
// Determine whether the queue is empty
IsEmpty: function (){
Return this. requests. length = 0;
}
}
}) (JQuery );
$. AjaxQueue. offer (settings) is used. The settings configuration is consistent with that in the jQuery document.
If you are interested, you can click my jsFiddle share to run and modify it online. If you have any questions, please contact us :)