- 用法与前面请求纯文本内容一致
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.user{
display:flex;
background: #f4f4f4;
padding:10px;
margin-bottom:10px;
}
.user ul{
list-style: none;
}
</style>
</head>
<body>
<button id="btn">请求github接口</button>
<br>
<h1>所有github的用户信息</h1>
<div id="users"></div>
<script>
document.getElementById("btn").addEventListener("click",loadUsers);
function loadUsers(){
let xhr = new XMLHttpRequest();
xhr.open("GET","https://api.github.com/users",true);
xhr.onload = function(){
let users = JSON.parse(this.responseText);
let output = '';
for(let i in users){
output += `
<div class= "user">
<img src="${users[i].avatar_url}" width="70" height="70"/>
<ul>
<li>ID:${users[i].id}</li>
<li>LOGIN:${users[i].login}</li>
</ul>
</div>
`;
}
document.getElementById("users").innerHTML = output;
}
xhr.send();
}
</script>
</body>
</html>
网友评论