Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (6.5 MB, 505 trang )
Chapter 17
JavaScript and XML
After reading this chapter, you’ll be able to:
n
Examine the functions for opening an Extensible Markup Language (XML) document
by using JavaScript.
n
Display an XML document as a Hypertext Markup Language (HTML) table.
n
View a Microsoft Office Excel 2007 XML spreadsheet by using JavaScript.
Using XML with JavaScript
XML is a language consisting almost completely of user-defined tags. Because the userdefined tags make XML extremely customizable, XML is frequently used as a file format for
exchanging data. An important consideration for JavaScript programmers is that XML is the
X in the acronym AJAX (Asynchronous JavaScript and XML). AJAX has become a very popular
method for creating interactive web applications. You learn more about AJAX in the next two
chapters: Chapter 19, “A Touch of AJAX,” and Chapter 20, “A Bit Deeper into AJAX.”
XML is an open standard defined by the World Wide Web Consortium (W3C) and is currently
in its fourth edition. This section looks briefly at XML as it pertains to JavaScript. You can find
more information about XML on the XML Working Group’s website at http://www.w3.org
/XML/Core/, or on Microsoft’s website at http://msdn.microsoft.com/xml/.
Looking at an Example XML Document
XML documents consist of elements within a document structure. These elements have syntax rules of their own, including that they need a start tag and an end tag. To the web programmer, the look of a document (defined in the text between tags) might be familiar. Here’s
an example XML document, also provided in the books.xml file in the Chapter17 folder in the
companion content:
331
332
Part IV AJAX and Server-Side Integration
The structure of the document as a whole needs to meet certain criteria to qualify as a wellformed document. As you can see in the example, each element has its own start tag followed
by a corresponding end tag. Elements also can be nested within each other. Many of these
rules are similar to HTML rules.
XML documents can contain attributes as well, so the following is also valid:
publisher="Microsoft Press" />
Loading an XML Document with JavaScript
You can load and manipulate XML documents using JavaScript. This section looks at doing
just that.
Importing the Document
You can import an XML document using one of two approaches, depending on the browsers you’re supporting. For newer browsers, including Chrome, Firefox, and later versions
of Windows Internet Explorer, you can use the XMLHTTPRequest() object, whereas older
versions of Internet Explorer use the ActiveXObject object. The following code loads the
books.xml document in a cross-browser manner:
if (window.XMLHttpRequest) {
var httpObj = new XMLHttpRequest();
} else {
var httpObj = new ActiveXObject("Microsoft.XMLHTTP");
}
httpObj.open("GET","books.xml",false);
httpObj.send();
var xmlDocument = httpObj.responseXML;
Chapter 17 JavaScript and XML
333
Displaying the Document
Often, XML data can best be visualized in a table or spreadsheet format. Figure 17-1 shows
the books.xml file in Excel 2007.
Figure 17-1 An XML file represented in a spreadsheet.
An HTML table is helpful for representing in a browser the same data shown in Figure 17-1. In
large part, displaying XML data using JavaScript requires some knowledge of the Document
Object Model (DOM), but no other special functions or methods beyond those needed to
load the document itself, which you already learned about.
The next example creates a function called displayData() that displays information in a
tabular manner.
334
Part IV AJAX and Server-Side Integration
The readyState Property
Previous versions of this book used the readyState property to determine when the
XML document was loaded. The readyState property is an integer that holds one of
five values indicating the current state of the document request being processed. Table
17-1 shows the values and corresponding descriptions of readyState.
Table 17-1 The
readyState Property
Value
Description
0
Uninitialized. Open but has yet to be called.
1
Open. Initialized but not yet sent.
2
Sent. The request has been sent.
3
Receiving. The response is actively being received.
4
Loaded. The response has been fully received.
You learn more about the readyState property and the onreadystatechange event in
Chapter 18, “JavaScript Applications.”
Displaying the nodes and child nodes within an XML document requires iterating through
the document’s levels and building the output document. The next function shown does
that by iterating through a hierarchical XML document to display that document’s data in an
HTML table. This code continues the example shown already, where a variable called xmlDocument is created and loaded with an XML document called books.xml:
function displayData(xmlDocument) {
var xmlEl = xmlDocument.getElementsByTagName("book");
var table = document.createElement("table");
table.border = "1";
var tbody = document.createElement("tbody");
// Append the body to the table
table.appendChild(tbody);
// Create the table cells for the new row
for (i = 0; i < xmlEl.length; i++) {
var row = document.createElement("tr");
// Create the row/td elements
for (j = 0; j < xmlEl[i].childNodes.length; j++) {
// Skip it if the type is not 1
if (xmlEl[i].childNodes[j].nodeType != 1) {
continue;
}
// Insert the actual text/data from the XML document.
var td = document.createElement("td");
var xmlData =
document.createTextNode(xmlEl[i].childNodes[j].firstChild.nodeValue);
Chapter 17 JavaScript and XML
335
td.appendChild(xmlData);
row.appendChild(td);
}
tbody.appendChild(row);
}
document.getElementById("xmldata").appendChild(table);
}
To put all the code together into a webpage, you attach to an event the functions that load
and display the XML file. Listing 17-1 (included in the listing17-1.html file in the companion
content) creates a new function called getXML and attaches it to the window object’s load
event. The code that attaches the event is in boldface type.
Listing 17-1 Displaying XML data in an HTML table.