AJAX XML
AJAX XML 实例
AJAX 可用来与 XML 进行交互式通信。
本节通过解析实例来使你了解AJAX是如何读取XML的信息的!
我们首先实例化或HttpRequest(XHR)对象实例化或创建JavaScript的对象:
xhr = new XMLHttpRequest();
但是,IE5和IE6XMLHttpRequest,您需要以不同的方式实例化它:
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> </td>"; } } xx = x[i].getElementsByTagName("ARTIST"); { try { txt = txt + "<td>" + xx[0].firstChild.nodeValue + "</td>"; } catch(er) { txt = txt + "<td> </td>"; } } txt = txt + "</tr>"; } txt = txt + "</table>"; document.getElementById('txtCDInfo').innerHTML = txt; } } xmlhttp.open("GET", url, true); xmlhttp.send(); }
AJAX 服务器
上面这个例子中使用的服务器实际上是 XML ,名为 ""。