1. 程式人生 > >【TP3.2】TP3.2下實現ajax分頁(原創+親測可用)

【TP3.2】TP3.2下實現ajax分頁(原創+親測可用)

條件 func edit syn model 多條 ade ges var

一,寫在最開始:ajax分頁的原理,是利用了js的ajax執行請求,獲取分頁list和分頁page 【代碼塊】,去替換頁面顯示數據的【代碼塊】

技術:js的ajax + TP3.2的fetch("Index/data")技術,僅此而已。

1、在Library\Think\ 目錄下直接加入以下代碼:Ajaxpage.class.php

<?php
/**
 * ajax分頁類,有namespace,使用方法:
 * 控制器直接$ajaxpage = new \Think\Ajaxpage($p1,$p2,$p3);
 * @param unknowtype
 * @return return_type
 * @author xzz  2018年4月27日上午8:49:19
 
*/ 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、TP3.2的控制器中:ajax_action 是ajax請求的路由,action是頁面請求的路由。我們直接訪問action

/**
     * 用戶行為列表,自定義的ajax分頁,使用方式不應該是頁面訪問,
     * 而應該是js的onload完成進行ajax初始化訪問 
     * @author xuzhengzong 2018/04/28
     */
    public function ajax_action($model=‘Action‘){
        //獲取列表數據
        //統計要查詢數據的數量
        $page_size = 10;       //評論固定10條
        $page = intval($_REQUEST[‘p‘]);
        $id = intval($_REQUEST[‘id‘]);
        if(empty($page))$page = 1;
        $limit = (($page-1)*$page_size).",".$page_size  ;
        
    //讓分頁支持多條件查詢 -- xuzhengzong 2018/04/28    
        $where[‘status‘] = array(‘gt‘,-1);
        //$_REQURST[‘cond‘] && $where[‘cond‘] = $_REQURST[‘cond‘]; //多條件查詢判斷
        $list = M($model)->where($where)->order(‘id desc‘)->limit($limit)->select();
        $count[0][‘count‘] = M($model)->where($where)->count("*");    
    //end
    
        $param = ‘‘;
        //$map[‘status‘] = array(‘gt‘,1);
        $Page       = new \Think\Ajaxpage($count[0][‘count‘],$page_size, index,$param);// 實例化分頁類 傳入總記錄數和每頁顯示的記錄數(25)
        $show       = $Page->show();// 分頁顯示輸出
        foreach($list as $k=>$v){
            $list[$k][‘status_text‘] = $v[‘type‘]==1?‘啟用‘:‘禁用‘;
        }
        
        $this->assign(‘_page‘,$show);
        $this->assign(‘_list‘, $list);
        $html[‘content‘] = $this->fetch(‘Ajax/action‘);
        $this->ajaxReturn($html);
    }
    /**
     * 用戶行為列表
     * @author
     */
    public function action(){
        //獲取列表數據
        $Action =   M(‘Action‘)->where(array(‘status‘=>array(‘gt‘,-1)));
        $this->meta_title = ‘用戶行為‘;
        $this->display();
    }

3、html && js:下面代碼我們知道,頁面document加載完,執行index(1)的方法請求第一個頁面的數據list和page分頁

<!-- 數據列表+ajax分頁 -->
 <div id="list" class="list">
    
 </div>

<script type="text/javascript">
/* 初始化加載action_ajax分頁數據 --xuzhengzong 2018/04/28 */
var init_id = 1;
index(init_id);     //初始化頁面 init_id==1
function index(id){
    var id = id;
    //把數據傳遞到要替換的控制器方法中
    $.ajax({
        url:/index.php/Admin/User/ajax_action,
        type:"GET",
        async:false,
        dataType:"JSON",
        //data:{‘p‘:id,‘id‘:deal_id},
        data:{p:id},
        success:function(data){
            $("#list").replaceWith(data.content);  //html塊替換html的div
        },
        error:function(data){
            console.log("4:ajax not run~");
        }
    });
}
</script>

4、核心:上面【data.content】,是加載下面的Ajax/action.html進行替換的。

Ajax/action.html:

<div id="list" class="list">
<!-- 用戶行為ajax分頁示例demo頁面 -->
<div class="data-table" id="data-table">
<table class="">
    <thead>
        <tr>
        <th class="row-selected row-selected"><input class="check-all" type="checkbox"/></th>
        <th class="">編號</th>
        <th class="">標識</th>
        <th class="">名稱</th>
        <th class="">類型</th>
        <th class="">規則</th>
        <th class="">狀態</th>
        <th class="">操作</th>
        </tr>
    </thead>
    <tbody>
        <volist name="_list" id="vo">
        <tr>
            <td><input class="ids" type="checkbox" name="ids[]" value="{$vo.id}" /></td>
            <td>{$vo.id} </td>
            <td>{$vo.name}</td>
            <td><a href="{:U(‘editAction?id=‘.$vo[‘id‘])}">{$vo.title}</a></td>
            <td><span>{:get_action_type($vo[‘type‘])}</span></td>
            <td>{$vo.remark}</td>
            <td>{$vo.status_text}</td>
            <td><a href="{:U(‘User/editAction?id=‘.$vo[‘id‘])}">編輯</a>
                <a href="{:U(‘User/setStatus?Model=action&ids=‘.$vo[‘id‘].‘&status=‘.abs(1-$vo[‘status‘]))}" class="ajax-get">{$vo.status|show_status_op}</a>
                <a href="{:U(‘User/setStatus?Model=action&status=-1&ids=‘.$vo[‘id‘])}" class="confirm ajax-get">刪除</a>
                </td>
        </tr>
        </volist>
    </tbody>
    </table>

    </div>
    <!-- 分頁 -->
    <div class="page">{$_page}</div>
    <!-- /分頁 -->
    
</div>

5、重點講解 為什麽 要存在Ajax/action.html文件

我們知道TP3.2的display()是輸出模板,而fetch()是接手模板,但是不渲染。 完了,還沒看明白自行查看TP的fetch()方法。

6、效果: 路由沒帶p參數,跳轉到第二頁咯。

技術分享圖片

【TP3.2】TP3.2下實現ajax分頁(原創+親測可用)