写一个ajax实现分页查询的例子
时间: 2024-05-15 20:19:01 浏览: 92
kkpager 实现ajax分页查询功能
好的,以下是一个基于ajax实现分页查询的例子:
HTML文件:
```
<!DOCTYPE html>
<html>
<head>
<title>Ajax Pagination Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
load_data();
function load_data(page){
$.ajax({
url: "fetch.php",
method: "POST",
data: {page:page},
success: function(data){
$('#pagination_data').html(data);
}
})
}
$(document).on('click', '.pagination_link', function(){
var page = $(this).attr("id");
load_data(page);
});
});
</script>
</head>
<body>
<div id="pagination_data"></div>
</body>
</html>
```
fetch.php文件:
```
<?php
//数据库连接信息
$host = "localhost";
$user = "username";
$password = "password";
$dbname = "database_name";
//创建连接
$conn = mysqli_connect($host, $user, $password, $dbname);
//如果连接失败则输出错误信息
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//设置每页显示的记录数
$record_per_page = 10;
//获取当前页码值
if(isset($_POST["page"])){
$page = $_POST["page"];
} else {
$page = 1;
}
//计算起始记录
$start_from = ($page-1) * $record_per_page;
//执行查询语句
$query = "SELECT * FROM table_name ORDER BY id DESC LIMIT $start_from, $record_per_page";
$result = mysqli_query($conn, $query);
//输出查询结果
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
echo "<div>".$row["name"]."</div>";
}
}
//计算总页数
$query = "SELECT COUNT(*) as total_records FROM table_name";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$total_records = $row["total_records"];
$total_pages = ceil($total_records / $record_per_page);
//输出分页链接
if($total_pages > 1){
for($i=1; $i<=$total_pages; $i++){
echo "<span class='pagination_link' style='cursor:pointer; padding:6px; border:1px solid #ccc;' id='".$i."'>".$i."</span>";
}
}
//关闭连接
mysqli_close($conn);
?>
```
在以上示例中,我们通过Ajax从服务器加载数据并将其分页显示。可以在fetch.php中更改查询语句和分页设置以适应不同的数据和页面布局需求。
阅读全文