到此就可以就发送请求读取服务器端的XML数据了,最后要做的就是处理数据了。关于XMLHttpRequest对象,请参考AboutXMLHttpRequestObject一文。
看例子:
//AjaxDemo.html
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<title>AsynchronousJavaScriptAndXML</title>
</head>
<body>
<scripttype="text/javascript">
varxmlHttp=null;
functionreadyStateChangeHandle()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
varxmlDOM=xmlHttp.responseXML;
varxmlRoot=xmlDOM.documentElement;
try
{
varxmlItem=xmlRoot.getElementsByTagName("item");
alert(xmlItem[0].firstChild.data);
}
catch(e)
{
alert(e.message);
}
}
}
}
functionajaxRequest()
{
if(window.XMLHttpRequest)
{
xmlHttp=newXMLHttpRequest();
}
elseif(window.ActiveXObject)
{
xmlHttp=newActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange=readyStateChangeHandle;
xmlHttp.open("GET","data.xml",true);
xmlHttp.send(null);
}
</script>
<inputtype="button"onclick="ajaxRequest()"value="TakemetotheworldofAJAX"/>
</body>
</html>
//data.xml
<?xmlversion="1.0"encoding="GB2312"?>
<root>
<item>WelcometotheworldofAJAX(AsynchronousJavaScriptAndXML)!</item>
</root>