【TP3.2】TP3.2下实现ajax分页(原创+亲测可用)

一,写在最开始: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参数,跳转到第二页咯。

原文地址:https://www.cnblogs.com/xuzhengzong/p/8967491.html

时间: 2024-08-11 01:35:04

【TP3.2】TP3.2下实现ajax分页(原创+亲测可用)的相关文章

linux下升级gcc的方法 – 亲测可用

由于工作主要平台换到了linux上,而linux因为源上没有比较新的gcc,只有4.7,而我们用到了C++11, 只好自己升级了,升级方法也比较简单,就是耗时间. 1.下载gcc最新的源码包 wget http://gcc.skazkaforyou.com/releases/gcc-4.9.1/gcc-4.9.1.tar.gz 2.解压缩 tar -xf gcc-4.9.1.tar.gz豪享博娱乐城 3. cd gcc-4.9.1 4.运行download_prerequisites脚本, ./

VCL下最好的皮肤控件AlphaControls 9.05 完美支持XE6 亲测可用

在传统的vcl编程中,因自带的控件效果太过普通,为了更好的用户体验和视觉效果往往会使用第三方的一些皮肤控件,这样的皮肤控件百度上一搜一大把,但往往不了解自己不使用过直接下载下来也是没有用的,因为这要涉及到控件版本 ID工具版本 操作系统 等多方因素配合使用,只有实际测试使用过才可定性. 本文提供的一款控件是经过实际测试过的 测试环境:Windows7 32位 ,Delphi xe6, AlphaControls 9.05 下载链接:http://binstyle.7958.com/down_18

php实现搜索和分页效果-亲测有效

php搜索+分页,单写容易,组合起来不容易,网上找了一下,代码不全,搜索和分页没有完全实现,经过自己的修改尝试,成功实现简单的搜索+分页功能. 效果如下: 下面是完整的代码!写在一个php页面里面即可!所需要做的修改就是你的数据库信息和表信息.即可实现上面图片同样的效果!感谢网上分享的网友,我在此基础上改出了自己想要的功能,因此也贴出来,想对有些朋友有帮助. <?php$wherelist=array();$urlist=array();if(!empty($_GET['id'])){$wher

Linux 下常见的四款chm查看器比较[转载+亲测可用]

在linux系统下阅读chm格式的电子书,着实要费一番周折.本文旨在介绍几款linu系统下的chm查看器,方便读者阅读. 一.CHMSEE ChmSee 由国人开发,程序基于 GTK2+,个头十分小巧,且对中文支持也很好.在功能方面,ChmSee 具有与 Firefox 类似的分页浏览标签,能够自动检测编码,可以收藏书签,以及设置字体等. 安装: sudo apt-get install chmsee(ubuntu 15.04 , 17.04可能找不到源,需要手动下载) 问题1:启动不了或者出现

Comet4J推技术在SSHE三大框架中应用-linux下亲测可用

Comet4J(Comet for Java)是一个纯粹基于AJAX(XMLHTTPRequest)的服务器推送框架,消息以JSON方式传递,具备长轮询.长连接.自动选择三种工作模式. 下载地址 comet4j.zip 我上传上原始的开发别的人开发包 在这里 功能特性 推送消息广播. 推送定向消息. 提供连接上线前.上线.下线前.下线.发送消息等多种可处理事件. 消息缓存机制,确保长轮询工作模式下不丢失消息. 客户端正常下线,服务端可立即感知. 客户端异常停止工作,服务端可定时检查并感知. 以注

Linux 下 zip 文件解压乱码解决方案,ubuntu16.10亲测可用

文章来源: https://www.zhihu.com/question/20523036 今天邮件中收到了一个压缩文件,解压后却是乱码,从网上也找了几个方法,目前这个方法还是比较可靠的,如下所示: 7z方案 需要安装p7zip和convmv,在Fedora下的命令是 su -c 'yum install p7zip convmv' 在ubuntu下的安装命令是 sudo apt-get install p7zip convmv 安装完之后,就可以用7za和convmv两个命令完成解压缩任务.

windows下mysql全备份及还原(亲测可用)

环境: 要备份的数据库ip为 192.168.28.1 账户 test1 ,密码 123456 本地数据库ip 为 192.168.28.2 账户 test1 ,密码 123456 全备份分为设置数据库主从同步和没设置主从同步 备份设置主从同步的数据库: @echo  off set "Ymd=%date:~,4%%date:~5,2%%date:~8,2%" "C:\Program Files\MySQL\MySQL Server 5.6\bin\mysqldump&quo

Linux下mysql的安装与卸载并且连接navicat详解(亲测可用)

哈喽,大家好,费了九牛二虎之力,终于完成了linux下用yum安装mysql,虽然出了很多错,但是最终成功可谓是不易,下面详细介绍下mysql的安装步骤: 一.卸载mysql 1.首先查看以前是否在linux上安装过mysql,如果有则需要先卸载干净. 首先使用命令查看虚拟机上是否存在mysql rpm -qa|grep -i mysql 如图所示,表示存在 2.停止mysql服务.删除之前安装的mysql 删除命令:rpm -e –nodeps 包名 如图所示: 如果提示依赖包错误,则使用以下

win7中python3.4下安装scrapy爬虫框架(亲测可用)

貌似最新的scrapy已经支持python3,但是错误挺多的,以下为在win7中的安装步骤: 1.首先需要安装Scrapy的依赖包,包括parsel, w3lib, cryptography, pyOpenSSL,twisted,lxml 其中,twisted和lxml的安装包可以在http://www.lfd.uci.edu/~gohlke/pythonlibs/下载对应的安装包(我的是win64,python34) pip install Twisted-17.1.0-cp34-cp34m-