AJAX - The Complete Reference

(avery) #1

420 Part II: Developing an Ajax Library^


When the response comes back, a few items are added to normalize the request:

_handleImageResponse : function(response){
response.httpStatus = 200;
response.httpStatusText = "OK";
if (response.cookieName)
response.responseText = AjaxTCR.comm.cookie.get(response.cookieName);
else
response.responseText = document.cookie;
response.responseXML = null;
AjaxTCR.comm._handleResponse(response);
},

There is one thing we should point out about the image technique: the result comes back
in the cookie value. If you want the library to automatically extract the value you are waiting
for, you need to pass the name of the cookie set by the server in during the request as the
option value cookieName. For example, the following invokes an image request indicating
that the answer should be returned back in a cookie value called "PollResults".

var url = "http://ajaxref.com/ch9/rate.php";
var options = { method: "GET",
transport: "image",
cookieName: "PollResults",
onSuccess : _handleCookie,
payload : "rating=" + rating };
AjaxTCR.comm.sendRequest(url,options);

Note that while this does populate the responseText property of the returned object, a
callback function with onSuccess is still invoked to handle the value. An outputTarget
could be specified instead, but this would require us to put fully formed HTML into the
cookie value to be directly inserted into the page. With the size limitations of cookies, this
doesn’t seem a terribly appealing idea, but it is certainly possible since transports should be
as transparent as possible to the library.
The changes necessary to handle the script transport have similar complexity. They are
shown here without running commentary for your inspection.

_sendScript : function(request){
var script = document.createElement("script");
var callback = function(){AjaxTCR.comm._handleScriptResponse(request);};
/* add optional transport indication */
if (request.transportIndicator)
{
if (request.url.indexOf("?"))
request.url += "&"+AjaxTCR.comm.DEFAULT_TRANSPORT_HEADER+"="+
AjaxTCR.comm.DEFAULT_SCRIPT_TRANSPORT_VALUE;
else
request.url += "?"+AjaxTCR.comm.DEFAULT_TRANSPORT_HEADER+"="+
AjaxTCR.comm.DEFAULT_SCRIPT_TRANSPORT_VALUE;
}
if (script.addEventListener)
script.addEventListener("load", callback, false);
else
Free download pdf