效果图
前台界面
*简单请求演示下,具体应用看需求,有了后台传递的json数据,前台可以为所欲为
<!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>php分页</title>
</head>
<body>
<script>
var xhr=new XMLHttpRequest();
xhr.open('get','show.php?curPage=1');
xhr.onload=function(){
console.log(xhr.responseText);
}
xhr.send(null);
</script>
</body>
</html>
后台处理
<?php
header('content-type:application/json;charset=utf-8');//设置浏览器解析格式为json
$curPage = $_GET['curPage'];//前台传递的当前页
$pageSize = 2;//页容量大小
$start = ($curPage - 1) * $pageSize;//起始页数
$totalPage = 0;//总页数
$con = mysql_connect("localhost", "root", "root");//数据库连接参数
mysql_select_db("s", $con);
$pageList = array();//用来封装分页数据的数组
//执行分页查询的同时在数据库中设置一个新字段,总记录数
$sql="SELECT * ,(select count(*)FROM stu )as total from stu limit $start,$pageSize";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
$items = array(
"id" => $row['id'],
"name" => $row['name'],
"age" => $row['age'],
"total" => $row['total']//
);
//总页数等于总记录数/页容量,向上取整, 如3.5页,要有第四页
$totalPage = ceil($row['total'] / $pageSize);
array_push($pageList, $items);//填充分页数据
}
mysql_close($con);//关闭连接
echo json_encode(array( //将数据以转为json形式响应到客户端
"curPage" => $curPage,//当前页
"pageList" => $pageList,//分页数据集合
"totalPage" => $totalPage//总页数
))
?>