原生ajax分页,无刷新分页,最简化。超简单,代码最少
<html>
<script>
var page=1;
// 页面第一次加载,显示第一页
window.onload=function(){
ajax_go(1)
}
//分页的代码
function ajax_go(type){
if (type==1) { //首页
page=1;
}else if (type=='prev') { //上一页
page=page-1>1?page-1:1;
}else if(type=='next'){ //下一页
page=page+1>max?max:page+1;
}else{ //尾页
page=max;
}
var str = ""
//ajax 核心代码
var xhr = new XMLHttpRequest;
xhr.open('get','getdata.php?p='+page)
xhr.send();
xhr.onreadystatechange=function(){
if (xhr.readyState==4&&xhr.status==200) {
var obj = JSON.parse(xhr.responseText)
// 数据
var data = obj['data'];
// 最大页码
max = obj['pages'];
//拼接要显示的数据
for (var i = 0; i < data.length; i++) {
str +="<tr>"
str +="<td>"+data[i]['id']+"</td>"
str += "<td>"+data[i]['goods_name']+"</td>"
str +="<td>"+data[i]['price']+"</td>"
str +="<td>"+data[i]['state']+"</td>"
str +="</tr>"
}
document.getElementById('content').innerHTML=str
document.getElementById('all').innerHTML=max
}
}
}
</script>
<body>
<table border="1">
<tr>
<th>id</th>
<th>标题</th>
<th>单价</th>
<th>状态</th>
</tr>
<tbody id="content">
</tbody>
</table>
<div>
共<span id='all'></span>页
<span><button onclick="ajax_go(1)">首页</button></span>
<span><button onclick="ajax_go('prev')">上一页</button></span>
<span><button onclick="ajax_go('next')">下一页</button></span>
<span><button onclick="ajax_go('end')">尾页</button></span>
</div>
</body>
</html>
下面是getdata.php:
<?php
$link = mysqli_connect("127.0.0.1", "root", "root", "news") or die("数据库连接失败!");
// 一、接收页码值
$p = $_GET["p"] ?? 1;
// 二、获取总条数
$sql = "select * from goods";
$result = mysqli_query($link, $sql);
$total = mysqli_num_rows($result);
// 三、计算偏移量
$size = 5; // 设置每页显示条数
$start = ($p - 1) * $size;
//四、 拼接sql语句
$page_sql = "select * from goods limit $start,$size";
$res = mysqli_query($link, $page_sql);
// 查询出分页的数据
while ($rows = mysqli_fetch_assoc($res)) {
$data[] = $rows;
}
// 总页数
$pages = ceil($total / $size);
// 把数组转为json字符串
echo json_encode(['pages' => $pages, 'data' => $data]);
?>
效果图: