<button id="button2">多个用户</button>
<br>
<hr>
<h1>多个用户</h1>
<div id="users"></div>
<script>
document.getElementById('button2').addEventListener("click",loadUsers);
function loadUsers(){
var xhr=new XMLHttpRequest();
xhr.open('GET',"user.php",true);
xhr.onload=function(){
if(this.status==200){
var users=JSON.parse(this.responseText);
console.log(users);
var output='';
//遍历数据
for( var i in users){
output+=`
<ul>
<li>${users[i].id}</li>
<li>${users[i].name}</li>
</ul>
`;
}
document.getElementById('users').innerhtml=output;
}
}
xhr.send();
}
</script>
user.php文件内容:
<?php
#链接数据库
$conn=MySQLi_connect("localhost","root","root","ajaxtext");
$query='select * from users';
$result=mysqli_query($conn,$query);
$users=mysqli_fetch_all($result,MYSQLI_ASSOC);
echo json_encode($users);
?>