Various solutions for multiple ajax requests (synchronization, queue, and cancel requests)

Source: Internet
Author: User

• Multiple ajax requests are sent at the same time and independent from each other.
• Multiple ajax requests are mutually dependent and must be sequenced.
• Multiple requests are sent at the same time. Only the last request is required.
1st Cases
Application Scenario: There are many scenarios. When a page is opened, multiple regions simultaneously request the backend to obtain their own data without dependency or order.
Solution: Use jquery's ajax function directly. This is widely used. For more information, see the examples in the code below.
2nd Cases
Application Scenario: Multiple ajax requests must be executed sequentially. The execution parameters of the latter ajax request are the results of the previous ajax request. For example, after a user logs on, we send a request to get the user's Application ID, and then use the Application ID to send a request to get the specific application content (although the example is not too appropriate, but it basically means this ).
Solution:
1. Use the ajax parameter async to set to false for synchronization. (This method is only applicable to operations in the same domain. The following two methods are required for cross-domain operations)
2. Use ajax nesting (this is the same as 1st Cases)
3. operate using queues
Core code of jquery ajax queue operation: Copy codeThe Code is as follows: (function ($ ){
Var ajaxRequest = {};
$. AjaxQueue = function (settings ){
Var options = $. extend ({className: 'defartname'}, $. ajaxSettings, settings );
Var _ complete = options. complete;
$. Extend (options ,{
Complete: function (){
If (_ complete)
_ Complete. apply (this, arguments );
If ($ (document). queue (options. className). length> 0 ){
$ (Document). dequeue (options. className );
} Else {
AjaxRequest [options. className] = false;
}
}
});
$ (Document). queue (options. className, function (){
$. Ajax (options );
});
If ($ (document). queue (options. className). length = 1 &&! AjaxRequest [options. className]) {
AjaxRequest [options. className] = true;
$ (Document). dequeue (options. className );
}
};
}) (JQuery );

3rd medium case
Application Scenario: the typical operation is the autocomplete control. We can use the processing method in 2nd cases, but we may only need the result returned after the last button, using 2nd processing methods is not a waste.
Processing Method: retain the last request before cancel.Copy codeThe Code is as follows: (function ($ ){
Var jqXhr = {};
$. AjaxSingle = function (settings ){
Var options = $. extend ({className: 'defartname'}, $. ajaxSettings, settings );
If (jqXhr [options. className]) {
JqXhr [options. className]. abort ();
}
JqXhr [options. className] = $. ajax (options );
};
}) (JQuery );

These cases are all in multiple ajax requests and the response time cannot be controlled. The following is the complete Demo code.Copy codeThe Code is as follows: (function ($ ){
Var jqXhr = {},
AjaxRequest = {};
$. AjaxQueue = function (settings ){
Var options = $. extend ({className: 'defartname'}, $. ajaxSettings, settings );
Var _ complete = options. complete;
$. Extend (options ,{
Complete: function (){
If (_ complete)
_ Complete. apply (this, arguments );
If ($ (document). queue (options. className). length> 0 ){
$ (Document). dequeue (options. className );
} Else {
AjaxRequest [options. className] = false;
}
}
});
$ (Document). queue (options. className, function (){
$. Ajax (options );
});
If ($ (document). queue (options. className). length = 1 &&! AjaxRequest [options. className]) {
AjaxRequest [options. className] = true;
$ (Document). dequeue (options. className );
}
};
$. AjaxSingle = function (settings ){
Var options = $. extend ({className: 'defartname'}, $. ajaxSettings, settings );
If (jqXhr [options. className]) {
JqXhr [options. className]. abort ();
}
JqXhr [options. className] = $. ajax (options );
};
}) (JQuery );
Var ajaxSleep = (function (){
Var _ settings = {
Type: 'get ',
Cache: false,
Success: function (msg ){
Var thtml = ('{txtcontainer'{.html ();
('{Txtcontainer'{.html (thtml + "<br/>" + msg );
}
};
Return {
Get: function (seconds, mode, isAsync ){
Var mode = mode | 'ajax ',
IsAsync = isAsync | false;
$ [Mode] ($. extend (_ settings ,{
Url: "ResponsePage. aspx? Second = "+ seconds,
Async: isAsync,
ClassName: 'get'
}));
},
Post: function (seconds, mode, isAsync ){
Var mode = mode | 'ajax ',
IsAsync = isAsync | false;
$ [Mode] ($. extend (_ settings ,{
Type: 'post ',
Url: "PostPage. aspx ",
Data: {second: seconds },
Async: isAsync,
ClassName: 'post'
}));
}
};
}());
Var launch = function (settings ){
('{Txtcontainer'{.html ('');
Var mode = settings. mode,
IsAsync = settings. isAsync;
AjaxSleep. get (12, mode, isAsync );
AjaxSleep. get (10, mode, isAsync );
AjaxSleep. get (8, mode, isAsync );
AjaxSleep. post (6, mode, isAsync );
AjaxSleep. post (4, mode, isAsync );
AjaxSleep. post (2, mode, isAsync );
}
$ (Document). ready (function (){
// There are 1st Cases
$ ('# BtnLaunchAsync'). click (function (){
Launch ({isAsync: true });
});
// There are 2nd Cases
$ ('# BtnLaunchSync'). click (function (){
Launch ({});
});
// There are 2nd Cases
$ ('# BtnLaunchQueue'). click (function (){
Launch ({mode: 'ajaxqueue ', isAsync: true });
});
// There are 3rd Cases
$ ('# BtnLaunchSingle'). click (function (){
Launch ({mode: 'ajaxsingle ', isAsync: true });
});
});

Default.htmlCopy codeThe Code is as follows: <! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head id = "Head1" runat = "server">
<Title> </title>
<Script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type = "text/javascript"> </script>
<Script type = "text/javascript" src = "js/default. js"> </script>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Input type = "button" id = "btnLaunchAsync" value = "Launch Asynchronous Request"/>
<Input type = "button" id = "btnLaunchSync" value = "Launch Synchronous Request"/>
<Input type = "button" id = "btnLaunchQueue" value = "Launch Requested Queue"/>
<Input type = "button" id = "btnLaunchSingle" value = "Launch Single Request"/>
<Div id = "txtContainer"> </div>
</Form>
</Body>
</Html>

PostPage. aspx & ResponsePage. aspxCopy codeThe Code is as follows: // ResponsePage. aspx
Protected void Page_Load (object sender, EventArgs e)
{
Int seconds = int. Parse (Request. QueryString ["second"]);
Thread. Sleep (seconds * 1000 );
Response. Write ("GET: selpt for" + seconds. ToString () + "sec (s )");
}
// PostPage. aspx
Protected void Page_Load (object sender, EventArgs e)
{
Int seconds = int. Parse (Request. Form ["second"]);
Thread. Sleep (seconds * 1000 );
Response. Write ("POST: selpt for" + seconds. ToString () + "sec (s )");
}

Post-Note: My personal abilities are limited. If you have any errors, please kindly advise. These are only some processing based on some specific circumstances. If an ajax request can solve the problem, do not use two requests for processing. After all, it takes up resources. I still believe that there is no best solution, only the most suitable one.

Related Article

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.