1. Trang chủ >
  2. Giáo án - Bài giảng >
  3. Tin học >

Part IV. AJAX and Server-Side Integration

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:





MySQL Bible

Steve Suehring

9780764549328

Wiley Publishing Inc.





JavaScript Step by Step

Steve Suehring











331



332



Part IV  AJAX and Server-Side Integration

9780735624498

Microsoft Press







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.


strict.dtd">





Books

















When viewed through a web browser, the table displays the data much like a spreadsheet

would, as shown in Figure 17-2.



Figure 17-2  Representing books.xml in an HTML table.



Examining the code from Listing 17-1 reveals a large for loop that walks through the XML

hierarchy, building table rows as it goes. One item to note is that the loop looks only for

Element nodes within the XML document by using this bit of code:







Chapter 17  JavaScript and XML



337



// Skip it if the type is not 1

if (xmlEl[i].childNodes[j].nodeType != 1) {

continue;

}



The nodeType of 1 represents an XML Element node. If the type of node currently being

examined in the loop is not an element, the code moves to the next part of the document.

One issue you may notice in the display in Figure 17-2 is that no column headings exist.

Adding column headings requires adding some code. The next procedure shows you how.



Adding column headings from an XML document





1. Using Microsoft Visual Studio, Eclipse, or another editor, edit the file books.htm in the

Chapter17 sample files folder, which you can find in the companion content. (At this

point in the procedure, when viewed through a web browser, books.htm should resemble Figure 17-2.)







2. Within books.htm, add the following code shown in boldface type to the displayData()

method (in the companion content in books.txt), replacing the TODO comment:


strict.dtd">





Books





















3. View the page in a web browser. It should look like this:







Chapter 17  JavaScript and XML



339



Working with XML Data from Excel 2007

Excel 2007 has several features that make working with XML data rather easy. Both importing

and exporting XML data is possible with Excel. In fact, when exporting data from Excel, Excel

adds nothing proprietary to the XML document. Here’s what the books.xml file looks like

when exported from Excel 2007 (included in the companion content as newbooks.xml):







MySQL Bible

Steve Suehring

9780764549328

Wiley Publishing Inc.





JavaScript Step by Step

Steve Suehring

9780735624498

Microsoft Press







Because Excel 2007 is XML-friendly, the displayData() function already examined in this chapter works with XML data exported from Excel 2007 without modification. For developers who

have worked with proprietary formats in the past, this comes as a welcome surprise.



340



Part IV  AJAX and Server-Side Integration



A Preview of Things to Come

Though XML is indeed the X in the AJAX acronym, there’s much more to AJAX than just

JavaScript and XML. AJAX can work with data types other than XML, and in Chapter 19, you

work with AJAX, building upon the brief foundation introduced in this chapter.

In Chapter 20, you examine the integration of JavaScript, AJAX, and Cascading Style Sheets

(CSS) that allows you to present data retrieved with JavaScript.



Exercises





1. Use the code from the book display exercise in this chapter to display the table after a

link is clicked rather than when the page loads.







2. Use the code from the book display exercise in this chapter to display the table, but use

the DOM to alternate the colors for each row so that every other row has a gray background. Hint: #aaabba is the hexadecimal representation of this gray color.



Xem Thêm
Tải bản đầy đủ (.pdf) (505 trang)

×