PHP AJAX 分页是一种使用 PHP 作为后端语言,结合 AJAX 技术实现网页数据分页的方法。它允许在不重新加载整个页面的情况下,动态地更新页面内容,从而提高用户体验。
适用于需要展示大量数据的网页,如新闻列表、商品列表、用户列表等。
<?php
// 数据库连接
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 获取当前页码,默认为第一页
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$limit = 10; // 每页显示的记录数
$offset = ($page - 1) * $limit;
// 查询数据
$sql = "SELECT * FROM table_name LIMIT $limit OFFSET $offset";
$result = $conn->query($sql);
$data = [];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
// 获取总记录数
$total_sql = "SELECT COUNT(*) as total FROM table_name";
$total_result = $conn->query($total_sql);
$total_row = $total_result->fetch_assoc();
$total = $total_row['total'];
// 计算总页数
$total_pages = ceil($total / $limit);
// 返回 JSON 数据
header('Content-Type: application/json');
echo json_encode([
'data' => $data,
'total' => $total,
'total_pages' => $total_pages,
'current_page' => $page
]);
$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AJAX 分页示例</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<table id="data-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div id="pagination">
<button id="prev-page">上一页</button>
<span id="current-page">1</span>
<button id="next-page">下一页</button>
</div>
<script>
let currentPage = 1;
const limit = 10;
function loadData(page) {
$.ajax({
url: 'path/to/your/php/file.php',
type: 'GET',
data: { page: page },
dataType: 'json',
success: function(response) {
const data = response.data;
const totalPages = response.total_pages;
const tableBody = $('#data-table tbody');
tableBody.empty();
data.forEach(function(item) {
tableBody.append(`<tr>
<td>${item.id}</td>
<td>${item.name}</td>
</tr>`);
});
$('#current-page').text(page);
currentPage = page;
if (page === 1) {
$('#prev-page').prop('disabled', true);
} else {
$('#prev-page').prop('disabled', false);
}
if (page === totalPages) {
$('#next-page').prop('disabled', true);
} else {
$('#next-page').prop('disabled', false);
}
}
});
}
$(document).ready(function() {
loadData(currentPage);
$('#prev-page').click(function() {
if (currentPage > 1) {
loadData(currentPage - 1);
}
});
$('#next-page').click(function() {
loadData(currentPage + 1);
});
});
</script>
</body>
</html>
通过以上步骤,你可以实现一个基本的 PHP AJAX 分页功能。如果遇到具体问题,可以根据错误信息和日志进行调试。
领取专属 10元无门槛券
手把手带您无忧上云