AJAX 最經典的用法之一,就是異步讀取服務器端的 XML 文件,再通過 DOM 解析其中的數據。下面是一個可直接運行的完整示例,點擊按鈕後讀取 data.XML,並彈出其中的內容。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>AJax Hello World</title>
<script type="text/Javascript">
var XMLHttp;
function createXMLHttpRequest(){
if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
}
function startRequest(){
createXMLHttpRequest();
try{
XMLHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET", "data.XML", true);
XMLHttp.send(null);
}catch(exception){
alert("您要訪問的資源不存在!");
}
}
function handleStateChange(){
if(XMLHttp.readyState == 4){
if (xmlHttp.status == 200 || XMLHttp.status == 0){
// 取得 XML 的 DOM 對象
var xmlDOM = xmlHttp.responseXML;
// 取得 XML 文檔的根
var root = XMLDOM.documentElement;
try {
// 取得 <info> 結果
var info = root.getElementsByTagName('info');
// 顯示返回結果
alert("responseXML's value: " + info[0].firstChild.data);
}catch(exception) {
}
}
}
}
</script>
</head>
<body>
<div>
<input type="button" value="return Ajax responseXML's value"
onclick="startRequest();" />
</div>
</body>
</html>
<?XML version="1.0" encoding="GB2312" ?>
<root>
<info>hello world!</info>
</root>
createXMLHttpRequest 兼顧 IE 的 ActiveX 與標準 XMLHttpRequest。startRequest 以異步(第三個參數為 true)方式 GET 請求 XML 文件。handleStateChange 中判斷 readyState == 4 且狀態正常後,通過 responseXML 拿到 DOM 對象。getElementsByTagName('info') 定位節點,再通過 firstChild.data 取出文本內容。與讀取 responseText 不同,responseXML 會把返回內容解析成可導航的 DOM 樹,特別適合結構化、層次清晰的數據交換場景。