首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Ajax >

PHP组合Ajax数字分页

2012-12-28 
PHP结合Ajax数字分页很久都没碰程序了,在无聊中写了一个PHP与Ajax相结合仿百度的数字分页,已经足以在日常

PHP结合Ajax数字分页
很久都没碰程序了,在无聊中写了一个PHP与Ajax相结合仿百度的数字分页,已经足以在日常中的运用,这里只是一个简单例子的实现,在项目运用过程中需要做一些改动,至于其改动方式得看你自己了,多余的不说了。
演示地址:http://www.phpcq.com/demo/pager.php
分页代码:
<?php
//Author:www.phpcq.com 
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>

热点排行