XMLHttpRequest Object (3)
Now we use the following code to fill the data from XML DOM object, and display
it an HTML table:
document.write("<table border='1'>");
var x=xmlDoc.getElementsByTagName("BOOK");
for (var i=0;i<x.length;i++){
document.write("<tr>");
document.write("<td>");
document.write(x[i].getElementsByTagName("AUTHOR")[0].childNodes[0].nodeValue);
document.write("</td>");
document.write("<td>");
document.write(x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue);
document.write("</td>");
document.write("</tr>");
}
document.write("</table>");
For each BOOK element in the XML document, a table row is created. Each table
row contains two table data cells with AUTHOR and TITLE data from the current
BOOK element.
The code below is part of the <head> section of the HTML file. It gets
the XML data from the first <BOOK> element and displays it in the HTML
element with the id="show":
var x=xmlDoc.getElementsByTagName("BOOK");
i=0;
function display()
{
artist=
(x[i].getElementsByTagName("AUTHOR")[0].childNodes[0].nodeValue);
title=
(x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue);
year=
(x[i].getElementsByTagName("LINK")[0].childNodes[0].nodeValue);
txt="Author: "+author+"<br />Title: "+title+"<br
/>Link: "+link;
document.getElementById("show").innerHTML=txt;
}
The body of the HTML document contains an onload eventattribute that will call
the display() function when the page has loaded. It also contains a <div
id='show'> element to receive the XML data.
<body onload="display()">
<div id='show'></div>
</body>
With the example above, you will only see data from the first BOOK element
in the XML document. To navigate to the next item of data, you should add navigation
to the example above, create two functions called next() and previous():
function next() {
if (i<x.length-1) {
i++;
display();
}
}
function previous() {
if (i>0) {
i--;
display();
}
}
The next() function makes sure that nothing is displayed if you already are
at the last BOOK element, and the previous () function makes sure that nothing
is displayed if you already are at the first BOOK element.
The next() and previous() functions are called by clicking next/previous buttons:
<input type="button" onclick="previous()" value="previous"
/>
<input type="button" onclick="next()" value="next"
/>
|