AJAX - The Complete Reference

(avery) #1

PART II


Chapter 6: Networking Considerations 247


code fragment here makes five requests to the same URL by adding them to the request
queue:

var url = "http://ajaxref.com/ch6/timeoutexplorer.php";
var numberRequests = 5;

var theRequests = new Array();
for (var i=1;i<= numberRequests;i++)
{
/* define communication options */
var options = { method: "GET",
onSuccess : showResponse,
queueID : i
};
/* make the request */
theRequests[i] = AjaxTCR.comm.queue.add(url,options);
}

It would be easy enough to queue up all sorts of requests to different URLs, but for the
purposes of this demonstration it isn’t required. You may want to note the queueID property.
This will be the request’s self-assigned queue sequence number. The name is somewhat
arbitrary, but it will be useful for keeping track of what the ID number is as opposed to what
is assigned by the library.
The add() method is quite straightforward. It uses a flag, inQueue, to determine if a
request is in the queue or not. Then it looks to see if it can send the request immediately or
if it should push the request to the queue for later processing. The method returns a
requestQueueID value, which can be used later to remove the item from the queue. An
outline of the queue code is shown here before it is made much more complex with
prioritizations:

/* simple version pre priority queue changes */
add : function(url, options) {
if (options)
options.inQueue = true;
else
options = {inQueue:true};

/* Add Id */
options.requestQueueID = ++AjaxTCR.comm.queue._requestQueueID;

/* See if we should send it or add it to the queue */
if (AjaxTCR.comm.stats.getRequestCount("active") >= AjaxTCR.comm.queue.
requestQueueConcurrentRequests) {
var request = {url: url, options: options};
AjaxTCR.comm.queue._requestQueue.push(request);
}
else
AjaxTCR.comm.sendRequest(url, options);

return options.requestQueueID;
}
Free download pdf