ajax数据请求4(xml格式):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>标题</title>
<meta name="keywords" content="">
<meta name="description" content="">
<style>
*{margin:0; padding:0; list-style:none;} </style>
</head>
<body>
<button id="btn">请求数据</button>
<ul id="list"></ul>
<script>
var btn=document.getElementById('btn');
var list=document.getElementById('list');
btn.onclick=function (){
// 1.创建XMLHttpRequest对象
var xhr=null;
if (window.XMLHttpRequest) {// 非IE5/6
xhr=new XMLHttpRequest();//实例对象
} else{// IE5/6
xhr=new ActiveXObject('Microsoft.XMLHTTP');
};
// 2.打开与服务器的链接
xhr.open('get','test04.xml?_='+new Date().getTime(),true);//生成不一样的url解决缓存问题
// 3.发送给服务器
xhr.send(null);//get请求
// 4.响应就绪
xhr.onreadystatechange=function (){
if (xhr.readyState==4) {//请求完成
if (xhr.status==200) {//ok
var xmlDoc=xhr.responseXML;
var names=xmlDoc.getElementsByTagName('name');
var sexs=xmlDoc.getElementsByTagName('sex');
var ages=xmlDoc.getElementsByTagName('age');
var scores=xmlDoc.getElementsByTagName('score');
for (var i = 0; i < names.length; i++) {
list.innerHTML+='<li>姓名:'+names[i].innerHTML+', 性别:'+sexs[i].innerHTML+', 年龄:'+ages[i].innerHTML+', 成绩:'+scores[i].innerHTML+'</li>';
};
} else{
alert(xhr.status);
};
};
}
}
</script>
</body>
</html>
xml:
<persons>
<person>
<name>老王</name>
<sex>女</sex>
<age>19</age>
<score>66</score>
</person>
<person>
<name>老刘</name>
<sex>男</sex>
<age>23</age>
<score>75</score>
</person>
<person>
<name>老李</name>
<sex>女</sex>
<age>24</age>
<score>88</score>
</person>
<person>
<name>老张</name>
<sex>男</sex>
<age>31</age>
<score>94</score>
</person>
</persons>