前端重新学习(14)javascipt之ajax代码实例(3)

Ajax-请求Github真实接口api接口

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>请求Github接口</title>
	<style>
		.user{
			display: flex;
			background: #f4f4f4;
			padding: 10px;
			margin-bottom: 10px;
		}

		.user ul{
			list-style: none;
		}

	</style>
</head>
<body>
	<button id="button">请求Github接口</button>

	<br><br>

	<h1>所有Github的用户信息</h1>

	<div id="users"></div>

	<script>
		document.getElementById('button').addEventListener('click',loadUsers);

		function loadUsers(){
			var xhr = new XMLHttpRequest();
			xhr.open("GET","https://api.github.com/users",true);

			xhr.onload = function(){
				var users = JSON.parse(this.responseText);//解析
				console.log(users);
				var output = '';
				for(var 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>

猜你喜欢

转载自blog.csdn.net/qq_16546829/article/details/81746343