May 08, 2021 AJAX
AJAX can be used to communicate interactively with XML files.
This section resolves instances to give you an understanding of how AJAX reads information about XML files!
Let's first instantiate or create XMLHttpRequest (XHR) objects or create JavaScript objects:
xhr = new XMLHttpRequest();
However, IE5 and IE6 do not support XMLHttpRequest, and you need to instantiate it in different ways:
xhr = new ActiveXObject ("Msxml2.XMLHTTP")
Note: T he Microsoft Edge default web browser that comes with Windows 10 naturally supports XMLHttpRequest. )
Therefore, instantiation of XHR becomes a bit cumbersome, and you must first test how the user's browser supports it.
var xhr;
if(window.XMLHttpRequest){ //适用于大多数现代Web浏览器
xhr = new XMLHttpRequest();
}
else(window.ActiveXObject){ //对于IE5,IE6
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
The following example shows how a Web page can use AJAX to read information from an XML file:
When the user clicks on the "Get CD information" button above, the
loadXMLDoc()
loadXMLDoc()
an XMLHttpRequest object, adds functions that are executed when the server is ready to respond, and sends requests to the server.
When the server is ready to respond, an HTML table is built, nodes (elements) are extracted from the XML file, and the
txtCDInfo
data:
function loadXMLDoc(url)
{
var xmlhttp;
var txt,xx,x,i;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
txt="<table border='1'><tr><th>Title</th><th>Artist</th></tr>";
x=xmlhttp.responseXML.documentElement.getElementsByTagName("CD");
for (i=0;i<x.length;i++)
{
txt=txt + "<tr>";
xx=x[i].getElementsByTagName("TITLE");
{
try
{
txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
}
catch (er)
{
txt=txt + "<td> </td>";
}
}
xx=x[i].getElementsByTagName("ARTIST");
{
try
{
txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
}
catch (er)
{
txt=txt + "<td> </td>";
}
}
txt=txt + "</tr>";
}
txt=txt + "</table>";
document.getElementById('txtCDInfo').innerHTML=txt;
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
The server page used in this example above is actually an XML cd_catalog.xml "1930".