index.html get_data.php两个文件
index.html
<!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>ajax study</title>
</head>
<body>
<div style="width:400px;margin:200px auto;">
<div id="result"></div>
</div>
<script>
function showList(page_id){
//创建ajax对象
var req='';
if(window.XMLHttpRequest)
req=new XMLHttpRequest();
else
req=new ActiveXObject("Msxml2.XMLHTTP");
req.open('get','get_data.php?page_id='+page_id);
req.onreadystatechange=function(){
if(req.readyState==4 && req.status==200){
document.getElementById('result').innerHTML=req.responseText;
}
}
req.send(null);
}
window.οnlοad=function(){
showList(1);
}
</script>
</body>
</html>
get_data.php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
//总记录数
$rs=$conn->query('select count(*) as count from tb_person');
if ($rs->num_rows > 0) {
$row = $rs->fetch_assoc();
}
$recordcount=$row['count'];
//页面大小
$pagesize=4;
//总页数
$pagecount=ceil($recordcount/$pagesize);
//获得当前页
$pageno=isset($_GET['page_id'])?$_GET['page_id']:1;
if($pageno<1)
$pageno=1;
if($pageno>$pagecount)
$pageno=$pagecount;
//起始位置
$startno=($pageno-1)*$pagesize;
$sql="select * from tb_person limit $startno,$pagesize";
$rs=$conn->query($sql);
if ($rs->num_rows > 0) {
echo '<ul>';
while ($row = $rs->fetch_assoc()) {
echo '<li><span>id:'.$row['id'].'</span> | <span>name:'.$row['name'].'</span></li>';
}
echo '</ul>';
for($i=1;$i<=$pagecount;$i++){
echo "<a href='javascript:void(0)' οnclick='showList($i)'>{$i}</a> ";
}
}
?>