04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 15: XML in JavaScript<br />

When an XML file is loaded asynchronously, you need to assign an onreadystatechange event handler<br />

to XML DOM document. There are four different ready states:<br />

❑<br />

❑<br />

❑<br />

❑<br />

1 — The DOM is loading data.<br />

2 — The DOM has completed loading the data.<br />

3 — The DOM may be used although some sections may not be available.<br />

4 — The DOM is completely loaded and ready to be used.<br />

Practically speaking, the only ready state of interest is 4, which indicates that the XML file has been<br />

completely downloaded and parsed into a DOM. You can retrieve the ready state of the XML document<br />

via the readyState property. Loading an XML file asynchronously typically uses the following pattern:<br />

var xmldom = createDocument();<br />

xmldom.async = true;<br />

xmldom.onreadystatechange = function(){<br />

if (xmldom.readyState == 4){<br />

if (xmldom.parseError != 0){<br />

alert(“An error occurred:\nError Code: “<br />

+ xmldom.parseError.errorCode + “\n”<br />

+ “Line: “ + xmldom.parseError.line + “\n”<br />

+ “Line Pos: “ + xmldom.parseError.linepos + “\n”<br />

+ “Reason: “ + xmldom.parseError.reason);<br />

} else {<br />

alert(xmldom.documentElement.tagName); //”root”<br />

alert(xmldom.documentElement.firstChild.tagName); //”child”<br />

var anotherChild = xmldom.createElement(“child”);<br />

xmldom.documentElement.appendChild(anotherChild);<br />

var children = xmldom.getElementsByTagName(“child”);<br />

alert(children.length); //2<br />

};<br />

}<br />

}<br />

alert(xmldom.xml);<br />

xmldom.load(“example.xml”);<br />

Note that the assignment of the onreadystatechange event handler must happen before the call to<br />

load() to ensure that it gets called in time. Also note that inside of the event handler, you must use the<br />

name of the XML document variable, xmldom , instead of the this object. ActiveX controls disallow the<br />

use of this as a security precaution. Once the ready state of the document reaches 4, you can safely<br />

check to see if there ’ s a parsing error and begin your XML processing.<br />

Even though it ’ s possible to load XML files via the XML DOM document object,<br />

it ’ s generally accepted to use an XMLHttpRequest object for this instead. The<br />

XMLHttpRequest object, and Ajax in general, are discussed in Chapter 17 .<br />

527

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!