TP2.0或3.1 或者 3.2 下使用ajax+php做無刷新分頁(轉+自創)


1.前言

    作為一名php程序員,我們開發網站主要就是為了客戶從客戶端進行體驗,在這里,thinkphp框架自帶的分頁類是每次翻頁都要刷新一下整個頁面,這種翻頁的用戶體驗顯然是不太理想的,我們希望每次翻頁只刷新我們想要的數據集部分的數據,這樣可以給客戶帶來很好的體驗效果。那么在TP下如何進行ajax無刷新分頁呢?

  1.1建立ajax分頁

    在TP框架的ThinkPHP\Library\Think文件夾下,有框架自己的page.class.php,我們新建一個Ajaxpage.class.php,下面這個類是我實際用到項目中的

        當然,你也可以不在這里建立,在需要的控制器方法里面可以 require_once "require_once APP_ROOT_PATH.'Ajaxpage.class.php';     //php加載ajax分頁類"

<?php
//【如果使用了TP3.2,請在這里加上namespace Think;】
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 = '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 = '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;
    }

}

?>

  2、ajax調用地址==》》 ajaxModule.class.php下的article_show_comment方法,返回結果:就是我們要替換的html數據和標簽(注意:這里我寫的是php的ajax方法,不是一個簡單的method,通俗點就是jQuery的ajax里面的url)

 

public function article_show_comment(){
        //統計要查詢數據的數量
        $page_size = 5;       //評論固定5條
        $page = intval($_REQUEST['p']);
        $id = intval($_REQUEST['id']);
        if(empty($page))$page = 1;
        $limit = (($page-1)*$page_size).",".$page_size    ;
         
        $list = $GLOBALS['db']->getAll("select * from ".DB_PREFIX."article_comment where article_id = ".$id." and log_id = 0 and status=1 order by create_time desc limit ".$limit);
        $count = $GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."article_comment where article_id = ".$id." and log_id = 0 and status=1");

//TP3.2使用下面 //$where['status'] = array('gt',-1); //$_REQURST['cond'] && $where['cond'] = $_REQURST['cond']; //多條件查詢判斷 // $list = M('Action')->where($where)->order('id desc')->limit($limit)->select(); // $count[0]['count'] = M('Action')->where($where)->count("*"); //end TP3.2  

        //實例化分頁類,傳入三個參數,分別是總記錄數、每頁顯示條數、要調用的jQuery ajax方法名
        require_once APP_ROOT_PATH.'app/Lib/Ajaxpage.class.php';     //php加載ajax分頁類
        $p = new Ajaxpage($count[0]['count'],$page_size,'index');   //'index'是jQuery里面ajax方法名
        //產生分頁信息
        $page=$p->show();
        //要查詢的數據,limit表示每頁查詢的數量,這里為10條
        //$data = $info->where($where)->limit($p->firstRow.','.$p->listRows)->select();
        //assign方法往模板賦值
        $GLOBALS['tmpl']->assign('list',$list);      //模板變量賦值
        $GLOBALS['tmpl']->assign('page',$page);
        //ajax返回信息,就是要替換的模板
        $res["content"] = $GLOBALS['tmpl']->fetch("article_show_comment.html");     //渲染模板,不輸出但是接收模板內容(得到html塊,用於替換主頁面的分頁div)
        echo json_encode($res);
    }

 

  3、模板文件【deal_show.html】

直接在原模板文件</body>之前加上ajax方法,用來翻頁作用,代碼如下:

<!-- ajax+php分頁 -xzz5.11 -->
<script type="text/javascript">
$(function(){
		var init_id = 1;     
		index(init_id);		//初始化頁面 init_id==1
});

function index(id){
    var id = id;
    var deal_id = {$deal_info.id}; //把數據傳遞到要替換的控制器方法中,這里你還可以傳入查詢字段,比如phone,name等,后台通過【是否為空】來做過濾
    $.ajax({
    	url:"/index.php?ctl=ajax&act=deal_show_comment",
    	type:"GET",
    	async:false,
    	dataType:"JSON",
    	data:{'p':id,'id':deal_id},  //把查詢字段和值 通過這里傳給后台ajax,實現多條件ajax查詢分頁
    	success:function(data){
    		//用get方法發送信息到ajax中的deal_show_comment方法
        	$("#pagination").replaceWith(data.content);  //html塊替換html的div
    	},
    	error:function(data){
    		console.log("4:ajax not run~");
    	}
    });
}
</script>

  4、注意啦,你應該還有一個頁面【article_show_comment.html】,就是php進行  $this->assign("list",$list);

  fetch()非常關鍵,獲取的list和page數據渲染后的模板html文件,但是不輸出,這里是關鍵點。====>>>>>>>>>>重中之重,fetch()的結果是:html塊,用來替換deal_show.html的分頁塊

  我們的目的:把獨立的【rticle_show_comment.html】文件,去替換【deal_show.html】文件里面的<div>,看好哦,是【deal_show.html】展示分頁數據list和分頁$page的<div>。 明白了這個你就成功一半了。

  使用TP的fetch()方法,在上面的ajaxModule.class.php的方法已經介紹了,在末尾部分,不懂自行查看TP手冊fetch()

  這里就給出替換內容的article_show_comment.html(ajax動態生成DOM,原來的關聯js無效,所以再次引入即可)。

<div id="pagination">
<div class="blank0"></div>
{foreach from=$list item=comment_item}
{include file="inc/comment_item_nolog.html"}   <!-- 這里的話,就是php另外引入的一個html文件,用來循環數據,在我的項目里他和下面的js有關聯 -->
{/foreach}
<div class="blank0"></div>
<div class="pages">{$page}</div>
</div>

<!-- 上面是動態生成的DOM,原html模板頁面的關聯js不生效,所以你沒ajax調用一次,就需要引入一下js -->
<script type="text/javascript"  src="{$TMPL}/js/deal_comment.js"></script>

  5、順便提一下,ajaxModule.class.php和XXXXModule.class.php完全是不同的2個控制器(因為TP2.0版本控制器就是Module,你要是TP3.1以后的,可以看成是AjaxController.class.php 都可以的),一個用來返回ajax請求的結果,一個是普通的控制器。

 

 6、在最后,順道感謝  小king哥,ThankU!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM