Ajax queue implemented by jQuery)

Source: Internet
Author: User
First, let's look at a requirement. There are two ajaxcalls on the page. One ajax requires the data of another ajax to operate. As described in the following code, $ (function () {vara_data; $. ajax ({url: test. php, success: function (data) {a_datadata ;},}); $. ajax ({url: test. ph

Let's take a look at the requirement. There are two ajax calls on the page. One ajax requires the data of another ajax to operate. As described in the following code

$ (Function (){
Var a_data;
$. Ajax ({
Url: "test. php ",
Success: function (data ){
A_data = data;
},
});
$. Ajax ({
Url: "test. php ",
Success: function (data ){
If (a_data = "5 "){
//....
}
},
});
});

The second ajax operation can be performed only after the first ajax data is processed. (Ps: Of course, the above statements are incorrect. Here we only describe this requirement)

I believe many people have encountered ajax queue problems. Fortunately, since jquery 1.3, there is a function that can well support queues, that is, queue.

Queue (name)
Returns the queue pointing to the First Matching Element (which will be a Function Array)

To implement ajax queues, you can introduce ajax into queue. The following code is implemented:

// The first ajax request
$ (Document). queue ("ajaxRequests", function (){
// Global variable, storing the first ajax request data
Var a_data;
$. Ajax ({
Success: function (data ){
A_data = data;
$ (Document). dequeue ("myName ");
}
});
});
// The second ajax request
$ (Document). queue ("ajaxRequests", function (){
$. Ajax ({
Success: function (data ){
Alert (a_data );
$ (Document). dequeue ("myName ");
}
});
});
// Trigger the queue to run down
$ (Document). dequeue ("ajaxRequests ");

The preceding Code implements the ajax queue, where two ajax requests are synchronously executed. dequeue is used to end the current ajax and call the next ajax request.

Next, let's take a look at the requirements of another ajax Queue (Requirement 2):
When verifying the email address and user name during registration, a single client can frequently send countless ajax requests, and our results must be subject to the last ajax request.
First, simulate a server page:

Sleep (5 );
Exit (time ().'');
?>

Next is the front-end page, which is triggered by an element:
Html code:





Test ajax queue


Click to trigger

Script
Script

JS Code:

$ (Function (){
$ ("Body"). queue ([]);
$ ("# Dtitle"). click (function (){
$ ("Body"). queue (function (){
$. Get ("test. php? T = "+ new Date (). getMilliseconds (), function (){
// This sentence allows the queue to run down;
$ ("Body"). dequeue ();
If ($ ("body"). queue (). length = 0)
Alert ("done ");
});
});
});
});

The following is the execution result of firebug. I click the dtitle element three times in a row and send a request every five seconds. Of course, this is only the principle of demonstration. Since three requests are sent, the last request must be taken as the standard. You can use the length attribute of the queue to perform round robin, And the length is changed to 0 at the moment, after all the requests are completed, you can execute the logic you want.

Okay. Through the above Code, we should have a certain understanding of queue usage and ajax queue. People always need to constantly pursue perfection. The crude Code cannot improve the Code level. Since queues are so commonly used, Do You Need To encapsulate this function? The answer is yes. Some plug-ins have been encapsulated on the Internet.
Rewrite $. ajax. Just do it:

(Function ($ ){
Var ajax = $. ajax,
PendingRequests = {},
Synced = [],
SyncedData = [],
AjaxRunning = [];
$. Ajax = function (settings ){
// Create settings for compatibility with ajaxSetup
Settings = jQuery. extend (settings, jQuery. extend ({}, jQuery. ajaxSettings, settings ));
Var port = settings. port;
Switch (settings. mode ){
Case "abort ":
If (pendingRequests [port]) {
PendingRequests [port]. abort ();
}
Return pendingRequests [port] = ajax. apply (this, arguments );
Case "queue ":
Var _ old = settings. complete;
Settings. complete = function (){
If (_ old ){
_ Old. apply (this, arguments );
}
If (jQuery ([ajax]). queue ("ajax" + port). length> 0 ){
JQuery ([ajax]). dequeue ("ajax" + port );
} Else {
AjaxRunning [port] = false;
}
};
JQuery ([ajax]). queue ("ajax" + port, function (){
Ajax (settings );
});
If (jQuery ([ajax]). queue ("ajax" + port). length = 1 &&! AjaxRunning [port]) {
AjaxRunning [port] = true;
JQuery ([ajax]). dequeue ("ajax" + port );
}
Return;
Case "sync ":
Var pos = synced. length;
Synced [pos] = {
Error: settings. error,
Success: settings. success,
Complete: settings. complete,
Done: false
};
SyncedData [pos] = {
Error: [],
Success: [],
Complete: []
};
Settings. error = function () {syncedData [pos]. error = arguments ;};
Settings. success = function () {syncedData [pos]. success = arguments ;};
Settings. complete = function (){
SyncedData [pos]. complete = arguments;
Synced [pos]. done = true;
If (pos = 0 |! Synced [pos-1])
For (var I = pos; I <synced. length & synced [I]. done; I ++ ){
If (synced [I]. error) synced [I]. error. apply (jQuery, syncedData [I]. error );
If (synced [I]. success) synced [I]. success. apply (jQuery, syncedData [I]. success );
If (synced [I]. complete) synced [I]. complete. apply (jQuery, syncedData [I]. complete );
Synced [I] = null;
SyncedData [I] = null;
}
};
}
Return ajax. apply (this, arguments );
};
}) (JQuery );

The preceding Code adds a mode variable with three values: "abort" (abort), "queue" (queue), and "sync.

For requirement 2, we use this encapsulated ajax to rewrite and improve it. The js Code section is as follows:

$ (Function (){
$ ("Body"). queue ([]);
$ ("# Dtitle"). click (function (){
$. Ajax ({
Url: "test. php? T = "+ new Date (). getMilliseconds (),
Success: function (html ){
JQuery ("ul"). append (html );
},
// Use abort instead of queue because the last ajax request is required, whereas the previous ajax request
// It is useless. Why wait for them to finish? You can stop it in the middle.
Mode: "abort"
});
});
});

Here, I believe you fully understand the ajax queue. Even if you don't understand it, you can directly use the encapsulated js Code and directly use mode: "abort"
You can.

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.