23.04.2013 Views

javascript

javascript

javascript

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 10 ■ SCRIPTING BOM<br />

434<br />

var div = createElem("div", {className: "scroller", id: "s2"}, [<br />

createElem("div", {className: "wrapper"}),<br />

createElem("div", {className: "left arrow sprite"}),<br />

createElem("div", {className: "right arrow sprite"})]);<br />

div.firstChild.innerHTML = req.responseText;<br />

document.body.appendChild(div);<br />

}<br />

getData("data/s3.xml", parseXML);<br />

}<br />

function parseXML(req) {<br />

prep();<br />

}<br />

An XML response differs from an HTML one in that it is a Document node containing Element and<br />

Text nodes rather than a string of plain text. So you query XML data the same way as a DOM tree. Yup,<br />

with the methods we covered in Chapter 7.<br />

So as you might guess, the DOM tree representing data/s3.xml isn’t in<br />

XMLHttpRequest.responseText. That value is a string not an object. Rather, the DOM tree for our XML is<br />

in XMLHttpRequest.responseXML. So after we make sure XMLHttpRequest.status is either 200 or 304, same<br />

as we did for HTML, we’ll save the DOM tree for our XML to a local variable named domTree.<br />

function parseXML(req) {<br />

if (req.status === 200 || req.status === 304) {<br />

var domTree = req.responseXML;<br />

}<br />

prep();<br />

}<br />

Note that if you are testing this script on your computer, which is to say loading URLs with the<br />

file:// protocol, there obviously will not be an http:// status code. So XMLHttpRequest.status will<br />

always be 0, no matter what. With this in mind, if you are testing the script on your computer, you must<br />

replace 200 or 304 with 0. Otherwise, the if block will never run!<br />

function parseXML(req) {<br />

if (req.status === 0 || req.status === 304) {<br />

var domTree = req.responseXML;<br />

}<br />

prep();<br />

}<br />

Now we want to save the nine Element nodes to a local variable named elements. Fetch<br />

those as if they were or elements—with Document.getElementsByTagName(), which we covered<br />

in Chapter 7:<br />

function parseXML(req) {<br />

if (req.status === 200 || req.status === 304) {<br />

var domTree = req.responseXML;<br />

var elements = domTree.getElementsByTagName("shoe");<br />

}<br />

prep();<br />

}<br />

Now for any of those elements, we can query the Text node in a child like so:<br />

elements[i].getElementsByTagName("href")[0].firstChild.data

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

Saved successfully!

Ooh no, something went wrong!