XML文档
<?xml version="1.0" encoding="utf-8"?>
<school>
<student>
<stuName>张三</stuName>
<stuNumb>1</stuNumb>
</student>
</school>
ajax.js
function initXHR(){
return window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
}
function testXHR(serverUrl,Parms,callBack){
var xhr = initXHR();//初始化XHR
var url = serverUrl+"?"+Parms+"&r="+Math.random();//初始化url
xhr.open("GET",url,true);//打开url
xhr.send(null);//发送请求
xhr.onreadystatechange = function(){
if(xhr.readyState==4) {
callBack(xhr);
}
}
}
js_xml.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ajax解析XML</title>
<script language="javascript" type="text/javascript" src="ajax.js">
</script>
<script language="javascript" type="text/javascript">
function jsToXML(){
testXHR("example.xml","",xmlTotable);
}
function xmlTotable(xhr){
var html = "<table border=1><tr>";
var XMLObj = xhr.responseXML;
var student = XMLObj.getElementsByTagName("student");
for(var i=1;i<6;i+=2){
html+="<th>"+student[0].childNodes[i].nodeName+"</th>";}
html +="</tr>";
for(var j=0;j<student.length;j++){
html+="<tr>";
for(var i=1;i<6;i+=2){
html+="<td>"+student[j].childNodes[i].firstChild.nodeValue+"</td>";
}
html+="</tr>";
}
html+="</table>";
document.getElementById("div").innerHTML=html;
}
</script>
</head>
<body>
<input type="button" value="解析xml" οnclick="jsToXML()" /><hr />
<div id="div"></div>
</body>
</html>