AJAX - The Complete Reference

(avery) #1

184 Part II: Applied Ajax^


request.xhr.onreadystatechange = function ()
{AjaxTCR.comm._handleResponse(request);};
}

Then, the request is sent on its way, using the XHR’s send() method and including any
post body.

/* send the request */
request.xhr.send(request.postBody);

If the request is synchronous, the code is of course blocked until it returns, so the callback
specified can be invoked immediately after.

if (!request.async)
AjaxTCR.comm._handleResponse(request);
} /* end of _makeRequest */

As we wind down our basic library overview, we inspect the private _handleResponse()
method. This method is mostly used to clear various flags and end timers. In the minimal
form, it would almost immediately send control to yet another private method
_handleCallbacks().

_handleResponse : function(response) {

/* Record end time of request */
response.endTime = (new Date()).getTime();

/* set a received flag to ensure you don't perform a
progress callback after received. */
response.received = true;

/* decrement outstand request count */
AjaxTCR.comm._requestsOutstanding--;

AjaxTCR.comm._handleCallbacks(response);
}

You might wonder what the point is with all these private methods and feel this is a bit
thin. There is, in fact, much more here if you examine the full library; we’re not showing
you the complete version yet for simplicity of discussion. The aim here is to show that
behind all the complex looking code in the final library, the actual skeleton of logic is exactly
the same as what was in the very first “Hello World” examples presented.
Finally, _handleCallbacks() looks at the status, making sure to avoid any known
browser problems, clears the flag indicating the request is in progress, decides to call the
success or failure callback, and nulls out the object for safe measure.

_handleCallbacks : function(response) {
/* check status to determine next move */
var status;

/* Danger: Firefox problems so we try-catch here */
try { status = response.xhr.status; } catch(e) {status=3507;}
Free download pdf