到此就可以就發送請求讀取服務器端的XML數據了,最後要做的就是處理數據了。 關於XMLHttpRequest對象,請參考About XMLHttpRequest Object一文。
看例子:
//AjaxDemo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Asynchronous JavaScript And XML</title>
</head>
<body>
<script type="text/javascript">
var xmlHttp=null;
function readyStateChangeHandle()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
var xmlDOM=xmlHttp.responseXML;
var xmlRoot=xmlDOM.documentElement;
try
{
var xmlItem=xmlRoot.getElementsByTagName("item");
alert(xmlItem[0].firstChild.data);
}
catch(e)
{
alert(e.message);
}
}
}
}
function ajaxRequest()
{
if(window.XMLHttpRequest)
{
xmlHttp=new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange=readyStateChangeHandle;
xmlHttp.open("GET","data.xml",true);
xmlHttp.send(null);
}
</script>
<input type="button" onclick="ajaxRequest()" value="Take me to the world of AJAX" />
</body>
</html>
//data.xml
<?xml version="1.0" encoding="GB2312" ?>
<root>
<item>Welcome to the world of AJAX(Asynchronous JavaScript And XML)!</item>
</root>