這是一個簡單範例的介紹,在實際應用中還可以再修改程式碼,讓分頁程式更完善。
程式碼如下:
建立一個test資料表,結構如下:
CREATE TABLE `test` (
`id` int(11) NOT NULL auto_increment,
`test` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 ;
pager.php 程式碼如下:
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
mysql_query("SET NAMES utf8");
$pageSize = 5;
$query = mysql_query("SELECT COUNT(*) AS count FROM test");
$count = mysql_fetch_object($query);
if("get" == $_GET['action']){
$offset = $_GET['offset'];
$size = ($offset - 1) * $pageSize;
$query = mysql_query("SELECT * FROM test ORDER BY id DESC LIMIT $size,$pageSize");
while($row = mysql_fetch_object($query)){
$row->count = $count->count;
$result[] = clone $row;
}
echo json_encode($result);
exit();
}
if("ajax"== $_GET['action']){
echo $count->count;//記錄總數
exit();
}
?>
index.php 程式碼如下:
<html>
<head>
<title>PHP+MySql結合Ajax分頁的範例</title>
<!--
<script type="text/javascript" src="jquery.js"></script>
-->
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js"></script>
<script>
$(document).ready(function(){
$.get('pager.php',{action:'ajax'},function(data){
var pagerString = '';
var pageSize = 5;
var countPage = Math.ceil(data / pageSize);
for(i = 1;i <= countPage && 10 >= i;i++){
if(1 == i){
pagerString += '<a>'+i+'</a> '
} else {
pagerString += '<a href="javascript:void(0)" onclick="paging('+i+')">'+i+'</a> '
}
}
$('#pager').html(pagerString);
});
});
function paging(page){
$.getJSON('pager.php',{offset:page,action:'get'},function(data){
var pagerString = '';
var htmlContentString = ''
var pageSize = 5;
var countPage = Math.ceil(data[0].count / pageSize);
$.each(data,function(i,n){
htmlContentString += '<p>id:'+n['id']+' Test:'+n['test']+'</P>';
});
for(i = page - 9;i <= page + 9 && i <= countPage;i++){
if(0 < i){
if(i == page){
pagerString += ' <a>'+i+'</a> '
} else {
pagerString += ' <a href="javascript:void(0)" onclick="paging('+i+')">'+i+'</a> '
}
}
}
$('#pager').html(pagerString);
$('#content').html(htmlContentString);
});
}
</script>
</head>
<body>
<div id="content">
<!-- results資料列表 -->
<?mysql_connect("localhost","root","");
mysql_select_db("test");
mysql_query("SET NAMES utf8");
$pageSize = 5;
$query = mysql_query("SELECT * FROM test ORDER BY id DESC LIMIT $pageSize");
while($row = mysql_fetch_object($query)){
$results[] = clone $row;
}
?>
<?php foreach($results as $values):?>
<p>id:<?php echo $values->id;?> Test:<?php echo $values->test;?></p>
<?php endforeach;?>
</div>
<div id="pager">
<!-- 分頁頁碼 -->
</div>
</body>
</html>
http://www.wretch.cc/blog/chuhsi0804/18904056
|