154 Part I: Core Ideas
When the XML data is received on the client side, you would read the contents of the
XHR’s responseXML property, as it contains a DOM tree representation of the packet, and
then use various DOM methods to pull out interesting pieces of content to use like so:
var xmlDoc = xhr.responseXML;
var average = xmlDoc.getElementsByTagName("average")[0].firstChild.nodeValue;
var total = xmlDoc.getElementsByTagName("votes")[0].firstChild.nodeValue;
var rating = xmlDoc.getElementsByTagName("rating")[0].firstChild.nodeValue;
As with previous examples, once you have the data you need, you can use either the
innerHTML property or standard DOM methods to update the page:
var responseOutput = document.getElementById("responseOutput");
responseOutput.innerHTML = "Thank you for voting. You rated this a
<strong>" + rating + "</strong>. There are <strong>" + total + "</strong>
total votes. The average is <strong>" + average + "</strong>. You can see
the ratings in the <a href='http://ajaxref.com/ch4/ratings.txt' target=
'_blank'>ratings file</a>.";
This example is pretty similar to previous XML examples, but interested readers can
find it at http://ajaxref.com/ch4/xmlresponse.html.
Now that the basics have been covered, let us address the value of using the XML format
from the angle of data integrity.
Well-Formed XML
Even if you are only aware of XML in passing, you likely know that it is quite strict in its
syntax. XML documents must be well-formed in order to be parsed. Well-formedness in
XML is defined by the following simple rules:
- The XML document must correctly identify itself.
- Tags must close even when empty.
- Tags must nest properly and not cross.
- Tags must match in case.
- Attributes on tags must be quoted.
- Special characters must be escaped.
Now, if an XHR receives malformed XML as a response, it will not populate the
responseXML property properly. In some browsers (Internet Explorer and Opera) it won’t
populate it at all, though in Firefox- and Safari-based browsers you will see a special error
document with a root node of <parsererror> in the property. Even in the presence of correct
XML markup, the MIME type of the response can affect things. Internet Explorer needs to see
application/xml or text/xml on the response to consider it XML. However, Opera 9 is
quite permissive and allows all sorts of other MIME types. Firefox and Safari also allow
application/xhtml+xml for valid responses. You can explore these actions directly with the
XML Explorer example found at http://ajaxref.com/ch4/xmlexplorer.html. A few examples of
its usage are shown in Figure 4-6.