zoukankan      html  css  js  c++  java
  • 【TP3.2】TP3.2下实现ajax分页(原创+亲测可用)

    一,写在最开始:ajax分页的原理,是利用了js的ajax执行请求,获取分页list和分页page 【代码块】,去替换页面显示数据的【代码块】

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

    1、在LibraryThink 目录下直接加入以下代码:Ajaxpage.class.php

    <?php
    /**
     * ajax分页类,有namespace,使用方法:
     * 控制器直接$ajaxpage = new ThinkAjaxpage($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 ThinkAjaxpage($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参数,跳转到第二页咯。

  • 相关阅读:
    装饰器
    异常处理与断言
    例子:对象构造函数指定类型传入参数(描述符与装饰器的应用)
    Python的描述符
    全新开始fighting
    函数相关知识
    集合的介绍以及简单方法
    列表,元组,字典类的常见简单方法
    Python简单字符串函数介绍
    聚合函数及分组查询及F&Q
  • 原文地址:https://www.cnblogs.com/xuzhengzong/p/8967491.html
Copyright © 2011-2022 走看看