AJAX - The Complete Reference

(avery) #1

PART II


Chapter 5: Developing an Ajax Library 225


Digging farther into the raw source code of jQuery, it is clear that it is a bit too trusting
in some Ajax details, at least in version 1.1.3. For example, the raw XHR instantiation is a
svelte statement of:

var xml = window.ActiveXObject? new ActiveXObject("Microsoft.XMLHTTP") :
new XMLHttpRequest();

This will, of course, favor the ActiveX implementation in Internet Explorer even in later
versions and will not address any latest version of the control a user may have. Similar other
details in terms of managing responses, dealing with response status, and readyState
changes could certainly be improved, but don’t give up on jQuery just yet as you’ll come to
understand why people like it so much in a short while.
Now, let’s return to the simple Ajax syntax example. When the response is received, the
registered handleResponse function will be invoked and passed any returned data. In this
case, since XML is returned, the contents of the XHR’s responseXML will be passed. jQuery
is nice in that it will look at the content returned and figure out what to do with it. However,
for more control, it is possible to set the dataType attribute to indicate that another type is
expected. Typically, the handleResponse() function would look something like this:

function handleResponse(responseXML)
{
var message = responseXML.getElementsByTagName("message")[0].firstChild.nodeValue;
var responseOutput = document.getElementById("responseOutput");
responseOutput.innerHTML = msg;
}

With jQuery, DOM manipulation is made much easier using the $() method. Unlike
some remappings of document.getElementById() to a shortened form, jQuery does a bit
more. First, $() takes both CSS and Xpath as parameters to select out elements and values
of interest and can work both on the main document as well as an XML response you have
received. To find the responseOutput tag that will hold the result, you would simply use
a CSS style ID selector like so:

$("#responseOutput")

To pull all the message element(s) out of the responseXML passed in, you would use:

$(responseXML, "message");

You could be more specific and pull out just the first message element:

$(responseXML, "message":eq(0));

or make it more readable as:

$(responseXML, "message":first);

To read out the text found in this tag, chain on a method text() to the returned jQuery
object:

var msg = $(responseXML, "message").text();
Free download pdf