給大家分享一個PHP與Ajax相結合仿百度的數字分頁,足夠大家日常使用,這裡只是一個簡單的例子,在使用過程中需要做小的修改,至於其改動方式得看你自己了。
分頁代碼:
<?PHP
mysql_connect(‘localhost’,'root’,”) or dIE(‘Host error!’);
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;
}
$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();
}
?>
<Html>
<head>
<title> This is a digital pager’s demo with PHP 、MySQL and AJax!</title>
<script type=”text/javascript” src=”jquery.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>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”>
<!–數據記錄–>
<?PHP foreach($results as $values):?>
<p>Test:<?PHP echo $values->test;?></p>
<?PHP endforeach;?>
</div>
<div id=”pager”>
<!–翻頁條碼–>
</div>
</body>
</Html>