只要代码没问题,基本上就没有问题,唯一值得注意的是虽然是html文档,但是如果想使用dom解析xml,还是必须使用服务器的,否则XMLHttpRequest 返回的status就是0了。

XML语言: studentdata.xml

0371

张三

17

0372

李四

18

0373

王五

18

HTML语言: domxml.html

使用DOM解析XML

"sendRequest();"/>

JavaScript语言: domxml.js

var XMLHttpReq;

var url = "studentdata.xml";

function createXMLHttpRequest() {

if (window.XMLHttpRequest)

XMLHttpReq = new XMLHttpRequest();

else if (window.ActiveXObject) {

try {

XMLHttpReq = new ActiveXObject("Msxml2.XMLHTTP");

}

catch (e) {

try {

XMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP");

}

catch (e) {

alert("create faile");

}

}

}

}

function sendRequest() {

createXMLHttpRequest();

XMLHttpReq.onreadystatechange = processResponse;

XMLHttpReq.open("GET", url, true);

XMLHttpReq.send(null);

}

function processResponse() {

if (XMLHttpReq.readyState == 4) {

if (XMLHttpReq.status == 200) {

readXml();

}

else {

window.alert(XMLHttpReq.statusText);

window.alert("请求页面有异常");

}

}

}

function readXml() {

// alert("start read");

var table = document.createElement("table");

table.setAttribute("border", "1");

table.setAttribute("width", "600");

document.body.appendChild(table);

var caption = "学生信息" + url;

table.createCaption().appendChild(document.createTextNode(caption));

var header = table.createTHead();

var headerrow = header.insertRow(0);

headerrow.insertCell(0).appendChild(document.createTextNode("学号"));

headerrow.insertCell(1).appendChild(document.createTextNode("姓名"));

headerrow.insertCell(2).appendChild(document.createTextNode("年龄"));

var students = XMLHttpReq.responseXML.getElementsByTagName("student");

for (var i =0; i < students.length; i++) {

var stud = students[i];

var sid = stud.getElementsByTagName("sid")[0].firstChild.data;

var sname = stud.getElementsByTagName("sname")[0].firstChild.data;

var sage = stud.getElementsByTagName("sage")[0].firstChild.data;

var row = table.insertRow(i + 1);

row.insertCell(0).appendChild(document.createTextNode(sid));

row.insertCell(1).appendChild(document.createTextNode(sname));

row.insertCell(2).appendChild(document.createTextNode(sage));

}

}


原文链接: https://blog.alswl.com/2009/02/ajax-started-use-dom-to-resolve-xml/
3a1ff193cee606bd1e2ea554a16353ee
欢迎关注我的微信公众号:窥豹

Comments

comments powered by Disqus