AjaxQ

AjaxQ
 点击下载

AjaxQ is a jQuery plugin that implements AJAX request queueing mechanism.

 
Why?
There are several reasons why you may need to queue AJAX requests and run them in a sequential manner:
 
Browsers impose a limit on the number of open connections to the server. All requests that do not fit in the limit are going to wait for being run anyway. Internet Explorer does not open more than 2 connections per server at a time by default. Mozilla Firefox, Opera and Safari have a limit of 8 connections per server.
Sometimes it is essential to avoid flooding the server with plenty of simultaneous AJAX requests.
Web application needs AJAX requests to run one by one by design, the order is important.
 
How?
Assume that the web application has to make two AJAX requests. Here's the usual and the simplest way of doing it:
  1. $.ajax ({ 
  2.     url: "test_1.html"
  3.     cache: false
  4.     success: function(html) 
  5.     { 
  6.         $("#results").append(html); 
  7.     } 
  8. }); 
  9.  
  10. $.ajax ({ 
  11.     url: "test_2.html"
  12.     cache: false
  13.     success: function(html) 
  14.     { 
  15.         $("#results").append(html); 
  16.     } 
  17. }); 
The requests will run almost simultaneously. Moreover, the response to the second request may come first.
Let's look at how to use AjaxQ plugin, and make the requests run in a sequential manner:
  1. $.ajaxq ("testqueue", { 
  2.     url: "test_1.html"
  3.     cache: false
  4.     success: function(html) 
  5.     { 
  6.         $("#results").append(html); 
  7.     } 
  8. }); 
  9.  
  10. $.ajaxq ("testqueue", { 
  11.     url: "test_2.html"
  12.     cache: false
  13.     success: function(html) 
  14.     { 
  15.         $("#results").append(html); 
  16.     } 
  17. }); 
Now the first requests runs first, and the second request runs only when the first one finishes.
There are only two essential differences between these two code blocks:
The method name changes from $.ajax() to $.ajaxq().
$.ajaxq() gets one more parameter, the name of the queue. Queue name comes first, and come second.
 
Notes
The number of AJAX queues is not limited. Web application may have as much AJAX queues as it requires. However, consider the limit of browser connections in case you have two or more queues running at the same time.
 
API
$.ajaxq (queue, options)
Enqueues a new AJAX request. The first parameter is a string denoting the name of the queue. The second parameter is a collection of request settings (see for details).
 
$.ajaxq (queue)
Stops the current AJAX request and clears the queue. The function parameter is a string denoting the name of the queue.

转载请注明:代码家园 » AjaxQ

评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)