Hi friends,
Lets say we have an XML file named "data.xml" as shown below.
<?xml version="1.0" encoding="utf-8" ?>
<speakers>
<speaker>
<name>LaVonne L. LaRue</name>
<shortname>LaVonne_LaRue</shortname>
<reknown>Chicago, IL</reknown>
<bio>LaVonne's giant-sized paintings all around Chicago tell the story of love, nature, and conversation - themes that are central to her heart. LaVonne will share her love and skill of graffiti art on Monday's schedule, as she starts the paintings of a 20-foot high wall in the Rousseau Room of Hotel Contempo in front of a standing-room only audience in Art in Unexpected Places.</bio>
</speaker>
<speaker>
<name>Samuel Deji Eniojukan</name>
<shortname>Sam</shortname>
<reknown>Atlanta, GA</reknown>
<bio>Sam is expert sharepoint architecture.</bio>
</speaker>
<speaker>
<name>Suraj Shrestha</name>
<shortname>Suraj</shortname>
<reknown>Boston, MA</reknown>
<bio>Suraj is expert .NET programmer.</bio>
</speaker>
<speaker>
<name>Hari Paudel</name>
<shortname>Honey</shortname>
<reknown>Jackson Heights, NY</reknown>
<bio>Hari is expert MVC developer.</bio>
</speaker>
<speaker>
<name>Merin Nakarmi</name>
<shortname>Merin</shortname>
<reknown>Atlanta, GA</reknown>
<bio>Merin is expert SharePoint and .NET Developer/Architecture.</bio>
</speaker>
<speaker>
<name>Tchelen Lilian Costa Nakarmi</name>
<shortname>Tchelen</shortname>
<reknown>Manaus, AM, Brazil</reknown>
<bio>Tchelen is sweet clarinest girl.</bio>
</speaker>
</speakers>
And we have a html file named index.html as shown below.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>JavaScript Ajax</title>
</head>
<body>
<h1>AJAX page</h1>
<div id="speakers">
</div>
<script src="script.js" type="text/javascript">
</script>
</body>
</html>
Now, we want to display the contents of the XML data file to a html page. We only want to display the list of name of speakers in the div with id "speakers". For this, we have an external JavaScript file named "script.js" as shown below.
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.open('GET', 'data.xml');
request.onreadystatechange = function () {
if((request.readyState === 4) && (request.status === 200))
{
var items = request.responseXML.getElementsByTagName('name');
var output = '<ul>';
for (var i = 0; i < items.length; i++) {
output += '<li>' + items[i].firstChild.nodeValue + '</li>';
}
output += '</ul>';
document.getElementById('update').innerHTML = output;
}
}
request.send();
The output of the html file would look like
No comments:
Post a Comment