<!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":"henry@gmail.com"
}
users.json
[
{
"id":1,
"name":"Henry",
"email":"henry@gmail.com"
},
{
"id":2,
"name":"Bucky",
"email":"bucky@gmail.com"
},
{
"id":3,
"name":"Hemiah",
"email":"27732357@qq.com"
}
]