158 Part I: Core Ideas
What about Internet Explorer? Well, it turns out for XML references, you need to use
IE’s own special nodeFromID() function. However, this function is not accessible from
responseXML. Instead, you must create an ActiveX XML DOM object and load in the raw
text from responseText to be parsed.
if (window.ActiveXObject)
{
xmlDoc=new ActiveXObject("MSXML2.DOMDocument.3.0");
xmlDoc.async="false";
xmlDoc.validateOnParse = false;
xmlDoc.loadXML(xhr.responseText);
}
NNOT EOTE You cannot use MSXML2.DOMDocument.6.0, as it does not access any DTDs.
Once you have your parsed DOM tree, you can use the nodeFromID() function
similarly to how you use getElementById():
var average = xmlDoc.nodeFromID ("average").firstChild.nodeValue;
var total = xmlDoc.nodeFromID ("votes").firstChild.nodeValue;
var rating = xmlDoc.nodeFromID ("rating").firstChild.nodeValue;
Given that there are two approaches to the getElementById() problem, you can
certainly guess that it is possible to abstract them away with a cross-browser wrapper
function as shown at http://ajaxref.com/ch4/xhtmlresponse.html.
In the previous example, you saw how to use XHTML to provide a method to use
getElementById()to access tags, but what if you prefer to use a rawer form of XML? Is it
possible to put the XHTML DOCTYPE statement on the response but keep the rest of the
syntax the same? Well, you might try a packet like:
<?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">
<rating id="rating">5</rating>
<average id="average">3.12</average>
<votes id="votes">1345</votes>
However, this won’t work because these tags aren’t defined in XHTML. However, you
can force the issue if you just wrap the packet inside of a <div> or similar tag in the XHTML
namespace and—presto—getElementById() will work in some browsers.
<?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">
<div xmlns="http://www.w3.org/1999/xhtml">
<rating id="rating">5</rating>
<average id="average">3.12</average>
<votes id="votes">1345</votes>
</div>