AJAX XML

AJAX XML 实例

AJAX 可用来与 XML 文件进行交互式通信。

本节通过解析实例来使你了解AJAX是如何读取XML文件的信息的!

我们首先实例化或创建XMLHttpRequest(XHR)对象实例化或创建JavaScript的对象: 

xhr = new XMLHttpRequest();

但是,IE5和IE6不支持XMLHttpRequest,您需要以不同的方式实例化它:

xhr = new ActiveXObject ("Msxml2.XMLHTTP")

注:Windows 10附带的Microsoft Edge默认Web浏览器自然支持XMLHttpRequest的。

因此,实例化XHR变得有点麻烦,你必须首先测试用户的浏览器如何支持它。

var xhr;
if(window.XMLHttpRequest) { //适用于大多数现代Web浏览器
    xhr = new XMLHttpRequest();
} else(window.ActiveXObject) { //对于IE5,IE6
    xhr = new ActiveXObject("Msxml2.XMLHTTP");
}

实例解析 - loadXMLDoc() 函数


当用户点击上面的"获得 CD 信息"这个按钮,就会执行loadXMLDoc()函数。

loadXMLDoc()函数创建 XMLHttpRequest 对象,添加当服务器响应就绪时执行的函数,并将请求发送到服务器。

当服务器响应就绪时,会构建一个 HTML 表格,从 XML 文件中提取节点(元素),最后使用已经填充了 XML 数据的 HTML 表格来更新txtCDInfo占位符:

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>&nbsp;</td>";
                    }
                }
                xx = x[i].getElementsByTagName("ARTIST"); {
                    try {
                        txt = txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
                    } catch(er) {
                        txt = txt + "<td>&nbsp;</td>";
                    }
                }
                txt = txt + "</tr>";
            }
            txt = txt + "</table>";
            document.getElementById('txtCDInfo').innerHTML = txt;
        }
    }
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

AJAX 服务器页面

上面这个例子中使用的服务器页面实际上是一个 XML 文件,名为 "cd_catalog.xml"。