php代码
<?php
//include "db_connect.php";
$db = new MySQLi("localhost", "root", "password", "paginate");
$db->set_charset('utf8mb4');
header('Content-type: application/json;charset=utf-8');
$total = 0; // 表格数据总行数
$per_page = 6; // 每页行数
$current_page = 1; // 当前显示第几页
$total_pages = 0; // 总页数
// 获取当前页数
if (!empty($_GET['current_page'])) {
$current_page = $_GET['current_page'];
}
// 获取表格数据总行数
$query1 = 'select count(*) from user';
$row1 = $db->query($query1);
if ($row1 && $rowd = $row1->fetch_row()) {
$total = $rowd[0];
}
// 获取总页数
$total_pages = ceil($total / $per_page);
// 分页
$pre = ($current_page - 1) * $per_page;
$query2 = "select * from user limit $pre,$per_page";
$rows = $db->query($query2);
$arr = [];
if($rows) {
$arr = $rows->fetch_all(MYSQLI_ASSOC);
}
$pagination = [
'total' => $total,
'per_page' => $per_page,
'current_page' => $current_page,
'total_pages' => $total_pages
];
array_push($arr, $pagination);
echo json_encode($arr, true);
postman截图:
js代码:
window.onload = function () {
getData(1);
}
function addURLParam(url, name, value) {
url += (url.indexOf("?") == -1 ? "?" : "&");
url += encodeURIComponent(name) + "=" + encodeURIComponent(value);
return url;
}
function getData(page) {
var data = document.getElementById("data");
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var jsonText = xhr.responseText;
console.log(JSON.parse(jsonText));
}
}
var url = "paginate.php";
url = addURLParam(url, "current_page", "page");
xhr.open("get", url, true);
xhr.send();
}
chrome console前面的数据库的内容均没有
应该是
$query2 = "select * from user limit $pre,$per_page";
$rows = $db->query($query2);
$arr = [];
if($rows) {
$arr = $rows->fetch_all(MYSQLI_ASSOC);
}
这里的sql出了问题,因为没加if($rows)之前会有错,然而我很奇怪为什么php可以正常运行,php版本是7.0.8
It’s a problem that js does not correctly pass parameters into addURLParam()
changed to
It’s really shameful to say that I discovered this bug after I posted the question. I edited and modified the question once, but the school had a power outage and the computer ran out of power, so I couldn’t test it. . . . . .
But the important point is that I added the addURLParam method last. It turned out to be direct
addURLParam() is a method in js advanced programming, it says
Friends who know the reason can answer this point, I will search it first~