DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> JavaScript入門知識 >> AJAX入門 >> AJAX詳解
用 AJAX 讀取 XML 格式數據的完整示例
編輯:AJAX詳解     

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(data.XML)

<?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 樹,特別適合結構化、層次清晰的數據交換場景。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved