ajax数据请求2(json格式)

时间:2021-10-01 02:01:37

ajax数据请求2(json格式)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ajax2(json格式)</title>
</head>
<body>
<button id="btn">数据请求</button>
<ul id="list"></ul>
<script type="text/javascript">
var btn = document.getElementById('btn');
var list = document.getElementById('list');
btn.onclick = function() {
//1.创建XMLHttpRequest对象
var xhr = null;
if(window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}else {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
//2.打开与服务器的链接
xhr.open('get','test2.json?_',true);
//3.发送给服务器
xhr.send(null);
//4.响应就绪
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
if(xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
// console.log(xhr.responseText);
for (var i = 0; i < json.name.length; i ++) {
// list.innerHTML += '<li>姓名:' + json.name[i] + ', 性别:' + json.sex[i] + ', 年龄:' + json.age[i] + ', 成绩:' + json.score[i] + '</li>';
list.innerHTML += '<li>姓名:' + json.name[i] + ', 性别:' + json.sex[i] + ', 年龄:' + json.age[i] + ', 成绩:' + json.score[i] + '</li>';
}
// console.log(json.name.length);
}else {
alert(xhr.status);
}
}
}
}
</script>
</body>
</html>

  json对象:

{
"name":["老王","老宋","老赵","老刘"],
"sex":["男","女","男","女"],
"age":[22,23,34,44],
"score":[66,77,88,99]
}