Thinkphp+Ajax 分頁

引言

眾所周知,Thinkphp有自帶的分頁功能,但主要是通過對(duì)網(wǎng)頁 的刷新實(shí)現(xiàn)。因?yàn)槊看嗡⑿戮W(wǎng)頁都需要加載靜態(tài)資源,程序開銷比較大。同時(shí),由于每次刷新網(wǎng)頁時(shí)頁面跳轉(zhuǎn)給用戶的體驗(yàn)感較差。所以,這里通過Ajax,實(shí)現(xiàn)網(wǎng)頁的局部刷新,不僅程序開銷減小,而且增強(qiáng)了用戶的體驗(yàn)。

方法

1. 首先在項(xiàng)目的Common中添加修改的分頁類

<?php
// +----------------------------------------------------------------------
//   Illustrate: 修改的AjaxPage 分頁類
// +----------------------------------------------------------------------
// 
namespace  Admin\Common;
class AjaxPage {
    // 分頁欄每頁顯示的頁數(shù)
    public $rollPage = 5;
    // 頁數(shù)跳轉(zhuǎn)時(shí)要帶的參數(shù)
    public $parameter  ;
    // 默認(rèn)列表每頁顯示行數(shù)
    public $listRows = 10;
    // 起始行數(shù)
    public $firstRow ;
    // 分頁總頁面數(shù)
    protected $totalPages  ;
    // 總行數(shù)
    protected $totalRows  ;
    // 當(dāng)前頁數(shù)
    protected $nowPage    ;
    // 分頁的欄的總頁數(shù)
    protected $coolPages   ;
    // 分頁顯示定制
    protected $config  = array('header'=>'條記錄','prev'=>'上一頁','next'=>'下一頁','first'=>'第一頁','last'=>'最后一頁','theme'=>' %totalRow% %header% %nowPage%/%totalPage% 頁 %upPage% %downPage% %first%  %prePage%  %linkPage%  %nextPage% %end%');
    // 默認(rèn)分頁變量名
    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);     //總頁數(shù)
        $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);     //總頁數(shù)
        $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 .= "&nbsp;<a class='ajaxify' id='big' href='javascript:".$this->ajax_func."(".$page.")'>&nbsp;".$page."&nbsp;</a>";
                }else{
                    break;
                }
            }else{
                if($this->totalPages != 1){
                    $linkPage .= "&nbsp;<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;
    }
}
?>

2. 在html中找到要刷新的局部頁面顯示代碼,然后在對(duì)應(yīng)的Controller下建立渲染模板

<div  id="temp">
    <form id="form"  name="form" method="post" action=""  onSubmit="click();">
       <div class="table-responsive" >
    <table class="table table-striped table-bordered table-hover">
        <thead>
        <tr   style="font-size:14.1px;">
        <th class="center"><input class="check-all" type="checkbox" value=""></th>
        </tr>
        </thead>
        <tbody>
        <volist name="list" id="val">
        <tr   id="record"  style="font-size:14.05px;">
            <td align="center">
               <input class="uids" type="checkbox"  name="uids[]" value="{$val['uid']}">
            </td>      
            <a <if condition="$val['l_check'] eq 1">
                href ="javascript:volid(0);"
             <else/>
                href="{:U('edit',array('uid'=>$val['uid']))}"
              </if>>修改</a>&nbsp;
             <a   data-name="{$val['uid']}"
              <if condition="$val['l_check'] eq 1">
                href ="javascript:volid(0);"
             <else/>
                  href="javascript:void(0);" onclick="delOneRecord(this)"
              </if>
                  title="刪除">刪除</a>
            </td>
        </tr>
        </volist>
        </tbody>
    </table>
    </div>
    </form>
    <div  class="page">
      {$page}
    </div>
</div>
  <!--如果對(duì)應(yīng)的AjaxPage頁面有相應(yīng)的Action操作,需要添加相應(yīng)的jquery或js方法,否則局部頁面刷新時(shí)不響應(yīng)-->
  <script type="text/javascript">
       function  delOneRecord(e)
       {
            bootbox.confirm({
                title: "系統(tǒng)提示",
                message: "是否要?jiǎng)h除所選記錄?",
                callback: function (result) {
                     var uids=e.getAttribute("data-name"); 
                     uids =  encodeURIComponent(uids);
                    $.get("{:U('del')}", {"uids":uids}, function(data)
                    {  
                            $(e).parents("tr").delay(500).fadeOut(700);
                    });
                },
                buttons: {
                    "cancel": {"label": "取消"},
                    "confirm": {
                        "label": "確定",
                        "className": "btn-danger"
                    }
                }
            });
        }
        $(".check-all").click(function () {
            $(".uids").prop("checked", this.checked);
        });
        $(".uids").click(function () {
            var option = $(".ids");
            option.each(function (i) {
                if (!this.checked) {
                    $(".check-all").prop("checked", false);
                    return false;
                } else {
                    $(".check-all").prop("checked", true);
                }
            });
        });
</script>

3. 控制器方法

public  function  getPageContent()
{         
   $uid  =intval(session('uid'));
   $inst = trim(session('inst'));
   $user = M();
   $count = count($user -> query("SELECT *,c.sex AS csex,m.sex AS msex from contractor as co join member as m on  co.uid=m.uid join chenglan_record as c on c.chl_name=co.cname where  m.uid = $uid  and c.chenglan_inst = $inst"));
   $p=new \Admin\Common\AjaxPage($count,10,"server");
   $limit_value = $p->firstRow . "," . $p->listRows;
   $list = $user -> query("SELECT *,c.sex AS csex,m.sex AS msex from contractor as co join member as m on  co.uid=m.uid join chenglan_record as c on c.chl_name=co.cname where  m.uid = $uid  and c.chenglan_inst = $inst   limit  $limit_value");
   //產(chǎn)生分頁信息
   $page=$p->show();
   $this->assign('list',$list);
   $this->assign('page',$page);
   $this->display();
  //判斷,如果是Ajax,返回局部頁面數(shù)據(jù)到前臺(tái)
   if(IS_AJAX)
  {
      $res["content"]=$this->fetch('ajaxPage');
      $this->ajaxReturn($res);
   }
}

4. js代碼

function server(id)
 {  
    var id = id;
    $.get("{:U('getPageContent')}", {"p":id}, function(data)
    {  
            $("#temp").replaceWith("<div id='temp'>"+data.content+" </div>");
    });
 }

5. 注意事項(xiàng)

  • Controller方法中的 $p=new \Admin\Common\AjaxPage($count,10,"server"); 第三個(gè)func參數(shù)要與js中func 名稱一致
  • 使用局部刷新時(shí),要將Page和要替換的模板放在一起。
  • 渲染模板要與替換模板一致,而且替換模板中的涉及到的js方法要在渲染模板中也要列出來。

6. 參考

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Swift1> Swift和OC的區(qū)別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴(yán)謹(jǐn) 對(duì)...
    cosWriter閱讀 11,659評(píng)論 1 32
  • 1.ios高性能編程 (1).內(nèi)層 最小的內(nèi)層平均值和峰值(2).耗電量 高效的算法和數(shù)據(jù)結(jié)構(gòu)(3).初始化時(shí)...
    歐辰_OSR閱讀 30,242評(píng)論 8 265
  • AngularJS是什么?AngularJs(后面就簡稱ng了)是一個(gè)用于設(shè)計(jì)動(dòng)態(tài)web應(yīng)用的結(jié)構(gòu)框架。首先,它是...
    200813閱讀 1,783評(píng)論 0 3
  • session與cookie的區(qū)別和聯(lián)系1.存放位置:Session保存在服務(wù)器,Cookie保存在客戶端。2.存...
    _fhs閱讀 968評(píng)論 0 1
  • 表情是什么,我認(rèn)為表情就是表現(xiàn)出來的情緒。表情可以傳達(dá)很多信息。高興了當(dāng)然就笑了,難過就哭了。兩者是相互影響密不可...
    Persistenc_6aea閱讀 129,655評(píng)論 2 7

友情鏈接更多精彩內(nèi)容