thinkphp下实现ajax无刷新分页

1.前言

    作为一名php程序员,我们开发网站主要就是为了客户从客户端进行体验,在这里,thinkphp框架自带的分页类是每次翻页都要刷新一下整个页面,这种翻页的用户体验显然是不太理想的,我们希望每次翻页只刷新我们想要的数据集部分的数据,这样可以给客户带来很好的体验效果。那么在TP下如何进行ajax无刷新分页呢?

  

   1.1建立ajax分页

    在TP框架的ThinkPHPLibraryThink文件夹下,有框架自己的page.class.php,我们新建一个Ajaxpage.class.php,下面这个类是我实际用到项目中的

  

<?php

namespace CommonCommon;
class AjaxPage {
    // 分页栏每页显示的页数
    public $rollPage = 5;
    // 页数跳转时要带的参数
    public $parameter  ;
    // 默认列表每页显示行数
    public $listRows = 20;
    // 起始行数
    public $firstRow ;
    // 分页总页面数
    protected $totalPages  ;
    // 总行数
    protected $totalRows  ;
    // 当前页数
    protected $nowPage    ;
    // 分页的栏的总页数
    protected $coolPages   ;
    // 分页显示定制
    protected $config  = array('header'=>'条记录','prev'=>'上一页','next'=>'下一页','first'=>'第一页','last'=>'最后一页',
  'theme'=>' %totalRow% %header% %nowPage%/%totalPage% 页 %upPage% %downPage% %first% %prePage% %linkPage% %nextPage% %end%'); // 默认分页变量名 protected $varPage; public function __construct($totalRows,$listRows='',$ajax_func,$parameter='') { $this->totalRows = $totalRows; $this->ajax_func = $ajax_func; $this->parameter = $parameter; $this->varPage = C('VAR_PAGE') ? C('VAR_PAGE') : 'p' ; if(!empty($listRows)) { $this->listRows = intval($listRows); } $this->totalPages = ceil($this->totalRows/$this->listRows); //总页数 $this->coolPages = ceil($this->totalPages/$this->rollPage); $this->nowPage = !empty($_GET[$this->varPage])?intval($_GET[$this->varPage]):1; if(!empty($this->totalPages) && $this->nowPage>$this->totalPages) { $this->nowPage = $this->totalPages; } $this->firstRow = $this->listRows*($this->nowPage-1); } public function nowpage($totalRows,$listRows='',$ajax_func,$parameter='') { $this->totalRows = $totalRows; $this->ajax_func = $ajax_func; $this->parameter = $parameter; $this->varPage = C('VAR_PAGE') ? C('VAR_PAGE') : 'p' ; if(!empty($listRows)) { $this->listRows = intval($listRows); } $this->totalPages = ceil($this->totalRows/$this->listRows); //总页数 $this->coolPages = ceil($this->totalPages/$this->rollPage); $this->nowPage = !empty($_GET[$this->varPage])?intval($_GET[$this->varPage]):1; if(!empty($this->totalPages) && $this->nowPage>$this->totalPages) { $this->nowPage = $this->totalPages; } $this->firstRow = $this->listRows*($this->nowPage-1); return $this->nowPage; } public function setConfig($name,$value) { if(isset($this->config[$name])) { $this->config[$name] = $value; } } public function show() { if(0 == $this->totalRows) return ''; $p = $this->varPage; $nowCoolPage = ceil($this->nowPage/$this->rollPage); $url = $_SERVER['REQUEST_URI'].(strpos($_SERVER['REQUEST_URI'],'?')?'':"?").$this->parameter; $parse = parse_url($url); if(isset($parse['query'])) { parse_str($parse['query'],$params); unset($params[$p]); $url = $parse['path'].'?'.http_build_query($params); } //上下翻页字符串 $upRow = $this->nowPage-1; $downRow = $this->nowPage+1; if ($upRow>0){ $upPage="<a class='ajaxify' id='big' href='JavaScript:".$this->ajax_func."(".$upRow.")'>".$this->config['prev']."</a>"; }else{ $upPage=""; } if ($downRow <= $this->totalPages){ $downPage="<a class='ajaxify' id='big' href='javascript:".$this->ajax_func."(".$downRow.")'>".$this->config['next']."</a>"; }else{ $downPage=""; } // << < > >> if($nowCoolPage == 1){ $theFirst = ""; $prePage = ""; }else{ $preRow = $this->nowPage-$this->rollPage; $prePage = "<a class='ajaxify' id='big' href='javascript:".$this->ajax_func."(".$preRow.")'>上".$this->rollPage."页</a>"; $theFirst = "<a class='ajaxify' id='big' href='javascript:".$this->ajax_func."(1)' >".$this->config['first']."</a>"; } if($nowCoolPage == $this->coolPages){ $nextPage = ""; $theEnd=""; }else{ $nextRow = $this->nowPage+$this->rollPage; $theEndRow = $this->totalPages; $nextPage = "<a class='ajaxify' id='big' href='javascript:".$this->ajax_func."(".$nextRow.")' >下".$this->rollPage."页</a>"; $theEnd = "<a class='ajaxify' id='big' href='javascript:".$this->ajax_func."(".$theEndRow.")' >".$this->config['last']."</a>"; } // 1 2 3 4 5 $linkPage = ""; for($i=1;$i<=$this->rollPage;$i++){ $page=($nowCoolPage-1)*$this->rollPage+$i; if($page!=$this->nowPage){ if($page<=$this->totalPages){ $linkPage .= " <a class='ajaxify' id='big' href='javascript:".$this->ajax_func."(".$page.")'> ".$page." </a>"; }else{ break; } }else{ if($this->totalPages != 1){ $linkPage .= " <span class='current'>".$page."</span>"; } } } $pageStr = str_replace( array('%header%','%nowPage%','%totalRow%','%totalPage%','%upPage%','%downPage%','%first%','%prePage%','%linkPage%','%nextPage%','%end%'), array($this->config['header'],$this->nowPage,$this->totalRows,$this->totalPages,$upPage,$downPage,$theFirst,$prePage,$linkPage,$nextPage,$theEnd),
          $this->config['theme']); return $pageStr; } } ?>

    •在这个类中,我们可以根据自己项目的需求,修改我们项目的分页情况$pageStr,默认列表每页显示行数等参数,非常方便,实际情况和page差不多,会用page,差不多就会改这个里面的很多参数,以及要写入confi的配置项。

  

    1.2 Controller处理

        //实例化数据模型
        $info=M('info');
        //统计要查询数据的数量
        $count=$info->where($where)->count();
        //实例化分页类,传入三个参数,分别是数据总数、每页显示的数据条数、要调用的jQuery ajax方法名
        $p=new HostCommonAjaxPage($count,10,'index');
        //产生分页信息
        $page=$p->show();
        //要查询的数据,limit表示每页查询的数量,这里为10条
        $data = $server_info->where($where)->limit($p->firstRow.','.$p->listRows)->select();
        //assign方法往模板赋值
        $this->assign('list',$data);
        $this->assign('page',$page);
        //ajax返回信息,就是要替换的模板
        $res["content"] = $this->fetch('Index/myinfolist')
        $this->ajaxReturn($res);

     

    1.3建立并且渲染模板

    myinfolist.html与要替换的模板一致。

    我们建立一个html,通过控制器,把数据渲染到模板中->

    然后通过 $res["content"] = $this->fetch('Index/myinfolist') 获取模板->

    最后通过js用渲染的模板去替换掉要替换的模板。

    

    1.4JS部分

    

function index(id){  
         var id = id;
            //把数据传递到要替换的控制器方法中
            $.get('/index/myinfo', {'p':id}, function(data){  
            //用get方法发送信息到index中的myinfo方法
             $("#server").replaceWith("<div  id='user7'>"
             +data.content+
             "</div>"); 
        });
    }

//data.content的内容就是$res["content"] = $this->fetch('Index/myinfolist') 获取的模板的内容

    •这个js中的index方法,必须和$p中的第三个参数保持一致(注意,一定要一样)

//实例化分页类,传入三个参数,分别是数据总数、每页显示的数据条数、要调用的jQuery ajax方法名
 $p=new HostCommonAjaxPage($count,10,'index');