HTML and CSS Reference
In-Depth Information
EXAMPLE
18.11 (
CONTINUED
)
<body>
<span style="cursor: pointer; text-decoration: underline"
13
onclick="makeRequest('http://localhost/bookstore.xml')
">
Get book details
</span>
14
<div id=data>
</div>
</body>
</html>
EXPLANATION
1
This function creates the
XMLHttpRequest
object, initializes it with the GET meth-
od and the XML file, called “bookstore.xml”, sends the request to the server, and
calls the
getXMLContents()
function when the state of the server changes to 4
(complete).
2
This function takes the
XMLHttpRequest
object as its argument. It is called when
the
onreadystatechange
event handler is notified that the server's
readyState
has
changed.
3
This function checks when the server has completed the request and fetches the
contents of the XML file.
The
httpRequest.responseXML
property contains the data returned from the XML file
as an XML document object.
4
5
The
getElementsByTagName()
method gets a reference to all the <
book
> tags stored
as an array in the XML object. Look at “bookstore.xml” to see the structure.
6
The outer for loop will iterate through each book in the array of books, called
booklist
.
7
The XML DOM
getAttribute()
method returns the value of an attribute by its
name, which is “category”.
8
For the name of each book,
childNodes[i].nodeName
, the
switch
statement will use
the
nodeValue
property to get the text for the title, author, and so on.
9
Using the DOM, elements are created that will be inserted in the
div
container on
line 14. A paragraph (
p
) and break (
br
) elements are created to hold the topic values.
10
Next, the
textNodes
are created that will be appended to the paragraph.
11
Once all the text nodes are created, they are appended to the paragraph with break
tags after each line of text.
12
Now, the new paragraph, built entirely with DOM methods, is inserted into the
div
container defined on line 14.
13
When the user clicks the underlined text, defined by the
<span>
tag, the Ajax pro-
gram is launched.
14
This is the
<div>
container that will display the output from the XML file returned
from the server. See Figure 18.15.