使用 AJAX 实现无刷新数据分页可以有效地提高网页的加载速度和用户体验。以下是一个简单的示例,展示了如何使用 AJAX 实现无刷新数据分页:
HTML 页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX 分页</title>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>
<div id="data-container">
<!-- 数据将通过Ajax填充到这里 -->
</div>
<div id="pagination">
<!-- 分页按钮将通过Ajax填充到这里 -->
</div>
<script>
$(document).ready(function() {
loadData(1); // 页面加载时加载第一页数据
});
function loadData(page) {
$.ajax({
url: 'get_data.php',
type: 'POST',
data: { action: 'get_data', page: page },
success: function(response) {
$('#data-container').html(response.dataHtml);
$('#pagination').html(response.paginationHtml);
}
});
}
// 点击分页按钮时触发
$(document).on('click', '.pagination-link', function() {
var page = $(this).data('page');
loadData(page);
});
</script>
</body>
</html>
PHP 后端脚本 (get_data.php)
<?php
include 'config.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$action = $_POST['action'];
if ($action === 'get_data') {
$currentPage = $_POST['page'];
$pageSize = 10; // 每页显示的条数
$result = getData($currentPage, $pageSize);
$dataHtml = generateDataHtml($result['data']);
$paginationHtml = generatePaginationHtml($result['totalPages'], $currentPage);
echo json_encode(['dataHtml' => $dataHtml, 'paginationHtml' => $paginationHtml]);
}
}
function getData($currentPage, $pageSize) {
global $conn;
$start = ($currentPage - 1) * $pageSize;
$sql = "SELECT * FROM your_table LIMIT $start, $pageSize";
$result = $conn->query($sql);
$data = [];
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
// 获取总页数
$totalRows = mysqli_num_rows($conn->query("SELECT * FROM your_table"));
$totalPages = ceil($totalRows / $pageSize);
return ['data' => $data, 'totalPages' => $totalPages];
}
function generateDataHtml($data) {
$html = '<ul>';
foreach ($data as $item) {
$html .= '<li>' . $item['column_name'] . '</li>';
}
$html .= '</ul>';
return $html;
}
function generatePaginationHtml($totalPages, $currentPage) {
$html = '<ul>';
for ($i = 1; $i <= $totalPages; $i++) {
$activeClass = ($i == $currentPage) ? 'class="active"' : '';
$html .= '<li><a href="#" data-page="' . $i . '" ' . $activeClass . ' class="pagination-link">' . $i . '</a></li>';
}
$html .= '</ul>';
return $html;
}
上述代码中的 your_table 和 column_name 需要替换成你实际的数据库表名和列名。
本站原创内容,如需转载请注明来源:https://www.liutonghui.com/134.html
评论列表(0条)
暂时没有评论!