I was not very busy at hand. I suddenly thought of the concept of ajaxqueue. I have read this in technical articles and I want to use jquery to implement it. The idea is simple and there is nothing complicated, an array object is used as a queue to maintain the order of ajax requests. The following code is provided:
The 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 :)