AJAX - The Complete Reference

(avery) #1

Chapter 4: Data Formats 157


PART I


The lack of validation of XML markup removes one of its great advantages as a data
format, that in theory at least, it would be possible to enforce syntax and semantics. Yet
there are even more issues to come that will irritate Ajax developers using the XML format
even if that were not the case.

XML and the DOM

One thing that Ajax developers quickly come to realize when dealing with XML responses
is that when using the standard DOM functions available in JavaScript, it can be a lot of
work. Developers often use the getElementsByTagName() method, or simply walk the
DOM tree. The ubiquitous getElementById() method is generally nowhere to be found
and for good reason—it does not seem to work. But is that really true?

XHTML and getElementById
Most JavaScript programmers are comfortable using the getElementById() method, so
much so that many employ libraries to create a similar function called $(). The interest in
this function is obvious since instead of having to walk a DOM tree, getElementById() or
any library similar function, gets you directly to the node that you wish to access. However,
if you try this method with a tree found in the responseXML property of an XHR object,
you will be disappointed to see that getElementById() simply does not work. In Internet
Explorer, the function is not even supported and will throw a JavaScript error when trying
to access it. It is supported in other browsers but will return a null object even if you have
the id attribute set on the node in question.
The reason getElementById() does not work in browsers is that it does not simply
look for something with an id attribute set to a particular text string; instead it looks for an
attribute called id that is of type ID. In XHTML or HTML this is preset for you. However, to
use an id attribute in your XML language, you would have to use a DTD or a schema and
declare or import it from another namespace. A natural thought then is to use an existing
DTD such as XHTML that declares the id attribute.
To experiment with this idea, you construct the response to look like a valid XHTML
document and set the id attribute on the nodes you wish to access the values for. For example:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Testing</title></head>
<body>
<div id="rating">5</div>
<div id="average">3.12</div>
<div id="votes">1345</div>
</body>
</html>

In non-IE browsers, you can then access the individual tags in the responseXML DOM
tree using the beloved getElementById() method:

var xmlDoc = xhr.responseXML;
var average = xmlDoc.getElementById("average").firstChild.nodeValue;
var total = xmlDoc.getElementById("votes").firstChild.nodeValue;
var rating = xmlDoc.getElementById("rating").firstChild.nodeValue;
Free download pdf