手把手教你實現thinkphp ajax無重新整理分頁

2021-09-20 19:01:13
下面教學欄目將給大家介紹怎麼實現thinkphp的ajax無重新整理分頁,希望對需要的朋友有所幫助!

前言

thinkphp框架自帶的分頁類是每次翻頁都要重新整理一下整個頁面,這種翻頁的使用者體驗顯然是不太理想的,我們希望每次翻頁只重新整理我們想要的資料集部分的資料,這樣我們很容易想到ajax非同步通訊,用ajax與資料庫(本人在開發過程中使用的是mysql資料庫)非同步互動,將從資料庫查詢的資料返回,用jquery替換原有的資料,從而在不重新整理這個頁面的情況下進行區域性重新整理,從而達到我們預期的效果。

thinkphp ajax 分頁類

這個分頁類是網上找到的資源,大家可以直接在自己的thinkphp裡建立這麼一個類,我這裡類名是 AjaxPage.class.php

<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <[email protected]>
// +----------------------------------------------------------------------
// $Id: Page.class.php 2712 2012-02-06 10:12:49Z liu21st $
namespace Common\Common;
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 .= "&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;
    }

}

?>

具體步驟

接下來,我們從控制器開始一步一步地實現thinkphp無重新整理分頁這個效果。

1.控制器部分

這只是控制器的一部分比較核心的程式碼。

        //範例化資料模型
        $info=M('info');
        //統計要查詢資料的數量
        $count=$info->where("ID='$id'")->count();
        //範例化分頁類,傳入三個引數,分別是資料總數、每頁顯示的資料條數、要呼叫的jQuery ajax方法名
        $p=new \Host\Common\AjaxPage($count,10,'server');
        //產生分頁資訊
        $page=$p->show();
        //要查詢的資料,limit表示每頁查詢的數量,這裡為10條
        $data = $server_info->where("ID='$id'")->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);

2.模板部分

模板名:myinfolist.html與上面控制器中渲染的模板一致。

 $res["content"] = $this->fetch('Index/myinfolist')

因為前端用的bootstrap框架,所以這個模板裡的好多class是bootstrap裡的,大家也不必過分糾結這個,看整個過程的重點就好。

<!DOCTYPE html>
<head>
</head>
    <p id="server">
        <p class="row-fluid"  >
            <p class="span12">
                <p class="portlet box green">
                    <p class="portlet-title">
                        <p class="caption"><i class="icon-globe"></i>資訊列表</p>
                    </p>

                    <p class="portlet-body" >
                
                        <table class="table table-striped table-bordered table-hover table-full-width" id="sample_1">

                            <thead>

                                <tr>
                                    <th class="hidden-480">a</th>
                                    <th class="hidden-480">b</th>
                                    <th class="hidden-480">c</th>
                                    <th class="hidden-480">d</th>
                                </tr>

                            </thead>

                            <tbody>
                                    //迴圈賦值
                                    <foreach name='list' item='info'>
                                        <tr>
                                            <td>{$info.a}</td>
                                            <td>{$info.b}</td>     
                                            <td>{$info.c}</td>
                                            <td>{$info.d}</td>
                                         
                                        </tr>
                                    </foreach>
                                
                            </tbody>
                            
                        </table>
                        //分頁資訊
                        <p class="row-fluid"> {$page} </p>
                        
                    </p>
                </p>    
            </p>        
        </p>
    </p>
    
    <script src="__PUBLIC__/server.js"></script> 
</html>

3.js部分

這一步是實現ajax無重新整理分頁的重點,用到了jQuery的ajax通訊,通過與資料庫的ajax互動,將獲取到的資料寫到模板中,替換掉之前的資料集,達到分頁的目的。
server.js

function server(id){  
         var id = id;
            $.get('/Server/myinfo', {'p':id}, function(data){  
            //用get方法傳送資訊到Server中的myinfo方法
             $("#server").replaceWith("<p  id='user7'>"
             +data.content+
             "</p>"); 
        });
    }

這個方法名 server 就是控制器中範例化分頁類中傳的第三個引數,每次在模板上點選翻頁,都會觸發這個js方法server(p),裡面傳遞的是第幾頁的頁碼。

$p=new \Host\Common\AjaxPage($count,10,'server');

這裡用到的是jQuery裡ajax方法的.get形式進行ajax與後臺通訊,拿到返回的資料用replaceWith方法,用

<p  id='user7'>+資料</p>

替換模板中id為server的p,實現分頁效果。

小結

上面的步驟就是實現ajax分頁的具體步驟,jQuery的ajax方法有$.ajax 、$.get 、 $.post三種,這裡就不做介紹,程式碼粘自我的程式中,為了不公開我的一些資料欄位,就用abcd代替了,也做了一定的刪減,有問題希望大家指正,多多交流。

以上就是手把手教你實現thinkphp ajax無重新整理分頁的詳細內容,更多請關注TW511.COM其它相關文章!