本文主要讲述在Ajax请求json的实例
实例和源码将在wamp64上面进行测试,编辑器使用sublime3
ajax.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax 2 - 请求JSON数据</title>
</head>
<body>
<button id="button1">请求单个用户</button>
<button id="button2">请求所有用户(遍历)</button>
<br><br>
<h1>单个用户</h1>
<div id="user"></div>
<h1>所有用户</h1>
<div id="users"></div>
<script>
document.getElementById('button1').addEventListener('click',loadUser);
document.getElementById('button2').addEventListener('click',loadUsers);
function loadUser(){
var xhr = new XMLHttpRequest();
xhr.open("GET","user.json",true);
xhr.onload = function(){
if (this.status == 200) {
console.log(this.responseText);//测试输出第一个数据
var user = JSON.parse(this.responseText);//数据解析
console.log(user.name);//测试解析后输出第一个数据属性
var output = '';
output +=
'<ul>'+
'<li>'+user.id+'</li>'+
'<li>'+user.name+'</li>'+
'<li>'+user.email+'</li>'+
'</ul>';
;
document.getElementById('user').innerHTML = output;
}
}
xhr.send();
}
function loadUsers(){
var xhr = new XMLHttpRequest();
xhr.open("GET","users.json",true);
xhr.onload = function(){
if (this.status == 200) {
var users = JSON.parse(this.responseText);
var output = '';
// 遍历数组
for(var i in users){
output +=
'<ul>'+
'<li>'+users[i].id+'</li>'+
'<li>'+users[i].name+'</li>'+
'<li>'+users[i].email+'</li>'+
'</ul>';
;
}
document.getElementById('users').innerHTML = output;
}
}
xhr.send();
}
</script>
</body>
</html>
user.json
[
{
"id":1,
"name":"Henry",
"email":"[email protected]"
},
{
"id":2,
"name":"Bucky",
"email":"[email protected]"
},
{
"id":3,
"name":"Hemiah",
"email":"[email protected]"
}
]