Jquer-ajaxQueue simple implementation code _ jquery

Source: Internet
Author: User
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 :)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.