详解thinkphp下部分内容的ajax无刷新分页

雨宇大大_7993

雨宇大大_7993

2022-01-31

2396人浏览

转载

下面thinkphp框架教程栏目将给大家介绍thinkphp下页面内部分内容的ajax无刷新分页,希望对需要的朋友有所帮助!

thinkphp框架自带的分页类是每次翻页都要刷新一下整个页面,这种翻页的用户体验显然是不太理想的,我们希望每次翻页只刷新我们想要的数据集部分的数据,这样我们很容易想到ajax异步通信,用ajax与数据库(本人在开发过程中使用的是mysql数据库)异步交互,将从数据库查询的数据返回,用jquery替换原有的数据,从而在不刷新这个页面的情况下进行局部刷新,从而达到我们预期的效果。
thinkphp ajax 分页类
这个分页类是网上找到的资源,大家可以直接在自己的thinkphp里创建这么一个类,我这里类名是 AjaxPage.class.php,如有需要,可修改命名空间

<?php 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 = 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>ajax_func."(".$upRow.")'>".$this->config['prev']."</a>";
    }else{
        $upPage="";
    }

    if ($downRow totalPages){
        $downPage="<a>ajax_func."(".$downRow.")'>".$this->config['next']."</a>";
    }else{
        $downPage="";
    }
    //  >>
    if($nowCoolPage == 1){
        $theFirst = "";
        $prePage = "";
    }else{
        $preRow =  $this->nowPage-$this->rollPage;
        $prePage = "<a>ajax_func."(".$preRow.")'>上".$this->rollPage."页</a>";
        $theFirst = "<a>ajax_func."(1)' >".$this->config['first']."</a>";
    }
    if($nowCoolPage == $this->coolPages){
        $nextPage = "";
        $theEnd="";
    }else{
        $nextRow = $this->nowPage+$this->rollPage;
        $theEndRow = $this->totalPages;
        $nextPage = "<a>ajax_func."(".$nextRow.")' >下".$this->rollPage."页</a>";
        $theEnd = "<a>ajax_func."(".$theEndRow.")' >".$this->config['last']."</a>";
    }
    // 1 2 3 4 5
    $linkPage = "";
    for($i=1;$irollPage;$i++){
        $page=($nowCoolPage-1)*$this->rollPage+$i;
        if($page!=$this->nowPage){
            if($pagetotalPages){
               $linkPage .= " <a>ajax_func."(".$page.")'> ".$page." </a>";
            }else{
                break;
            }
        }else{
            if($this->totalPages != 1){
                $linkPage .= " <span>".$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;
}

}

具体步骤
1.控制器
现在index方法里display,再在page方法里fetch,ajaxReturn,这里要注意fetch的是引用页(article)

<?php namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
    public function index(){
        $info=M('info');
        //统计要查询数据的数量
        $count=$info->count();
        //实例化分页类,传入三个参数,分别是数据总数、每页显示的数据条数、要调用的jQuery ajax方法名
        $p=new \Think\AjaxPage($count,4,'server');
        //产生分页信息
        $page=$p->show();
        //要查询的数据,limit表示每页查询的数量,这里为4条
        $data = $info->limit($p->firstRow.','.$p->listRows)->select();
        //assign方法往模板赋值
        $this->assign('list',$data);
        $this->assign('page',$page);
//        $res["content"] = $this->fetch('Index/index');
//        $this->ajaxReturn($res);
        $this->display();
    }
    public function page(){
        //实例化数据模型
        $info=M('info');
        //统计要查询数据的数量
        $count=$info->count();
        //实例化分页类,传入三个参数,分别是数据总数、每页显示的数据条数、要调用的jQuery ajax方法名
        $p=new \Think\AjaxPage($count,4,'server');
        //产生分页信息
        $page=$p->show();
        //要查询的数据,limit表示每页查询的数量,这里为4条
        $data = $info->limit($p->firstRow.','.$p->listRows)->select();
        //assign方法往模板赋值
        $this->assign('list',$data);
        $this->assign('page',$page);
        //ajax返回信息
        $res["content"] = $this->fetch('Index/article');
        $this->ajaxReturn($res);
    }
}

2.模板
柱模板 index.html

其中,引用的模板为需要分页的这部分内容

html>



<p>
    hello world
</p>
<include></include><script>
    function server(pid){  
        var pid = pid;
        $.get("{:U('Index/page')}", "p="+pid, function(data){  
             $("#server").replaceWith("<p  id='server'>"
             +data.content+
             ""); 
        });
    }
</script> 
<script></script>

需要分页的模板

article.html

AJAX技术—无刷新获取数据相关课件
AJAX技术—无刷新获取数据相关课件

AJAX技术—无刷新获取数据相关课件

下载
   <div>
        <div>
            <div>
                <div>
                    <div>
                        <div>
<i></i>信息列表</div>
                    </div>

                    <div>
                
                        <table>

                            <thead>

                                <tr>
                                    <th>a</th>
                                    <th>b</th>
                                    <th>c</th>
                                    <th>d</th>
                                </tr>

                            </thead>

                            <tbody>
                                    //循环赋值
                                    <foreach>
                                        <tr>
                                            <td>{$info.a}</td>
                                            <td>{$info.b}</td>     
                                            <td>{$info.c}</td>
                                            <td>{$info.d}</td>
                                         
                                        </tr>
                                    </foreach>
                                
                            </tbody>
                            
                        </table>
                        //分页信息
                        <div> {$page} </div>
                        
                    </div>
                </div>    
            </div>        
        </div>
</div>

这样就可以保证,点击页码的时候,不会导致分页内容上边的内容会再次加载一遍,造成网页乱

3.js部分
这一步是实现ajax无刷新分页的重点,用到了jQuery的ajax通信,通过与数据库的ajax交互,将获取到的数据写到模板中,替换掉之前的数据集,达到分页的目的。server.js  ,可写在内部也可写在外部,自由选择

 <script>
    function server(pid){  
        var pid = pid;
        $.get("{:U('Index/page')}", "p="+pid, function(data){  
             $("#server").replaceWith("<p  id='server'>"
             +data.content+
             ""); 
        });
    }
</script>

这个方法名 server 就是控制器中实例化分页类中传的第三个参数,每次在模板上点击翻页,都会触发这个js方法server(p),里面传递的是第几页的页码。

$p=new \Think\AjaxPage($count,4,'server');

这里用到的是jQuery里ajax方法的.get形式进行ajax与后台通信,拿到返回的数据用replaceWith方法,用

<div>+数据</div>

替换模板中id为server的p,实现分页效果。

推荐学习:《thinkphp视频教程》

php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!

相关文章

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

ajax thinkphp

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
GoFrame框架Web开发与路由中间件
GoFrame框架Web开发与路由中间件

本专题聚焦GoFrame框架的Web开发,拆解路由注册与匹配规则、请求参数获取、参数校验与中间件执行顺序,说明统一响应、JWT鉴权、文件上传与接口文档生成的落地方式,并补充优雅重启与测试实践。

2026.11.17

0

15

GoFrame框架安装与gf命令行工具
GoFrame框架安装与gf命令行工具

本专题围绕GoFrame框架的安装与工具链配置展开,讲清Go版本要求、gf命令行的安装方式、代理镜像与依赖准备,说明项目初始化、热编译、交叉编译打包的做法,并整理安装阶段的常见报错与验证步骤。

2026.11.17

0

15

GoFrame框架零基础入门
GoFrame框架零基础入门

本专题整理GoFrame框架的入门知识,从模块化设计理念、环境准备到跑通第一个Web服务,讲清目录分层、配置加载、日志与中间件的用法,并对比Gin、Go-Zero的差异,帮助Go开发者建立整体认知。

2026.11.17

0

15

SQLAlchemy 一对多关系怎么建立
SQLAlchemy 一对多关系怎么建立

SQLAlchemy 一对多关系怎么建立?本专题整理父子表外键、relationship 双向映射、关联查询、级联删除和加载优化等相关文章,帮助你理解并实现常见的 ORM 关系建模。

2026.11.17

0

10

SQLAlchemy 如何增删改查
SQLAlchemy 如何增删改查

SQLAlchemy 如何增删改查?本专题整理 ORM 新增记录、条件查询、更新和删除、Session 事务提交与批量处理等实用文章,帮助你掌握 Python 数据库操作流程。

2026.11.17

0

11

SQLAlchemy ORM 模型怎么写
SQLAlchemy ORM 模型怎么写

SQLAlchemy ORM 模型怎么写?本专题整理模型类定义、Mapped 字段映射、主键与约束、表结构创建和常见报错的相关文章,帮助你从基础配置到实际建模逐步掌握 SQLAlchemy。

2026.11.17

0

16

Go-Zero API开发使用教程
Go-Zero API开发使用教程

本专题聚焦Go-Zero的API开发,拆解.api描述文件的语法结构、路由与分组定义、参数绑定与校验规则,说明统一响应体、JWT鉴权、跨域与接口文档生成的落地方式,并给出网关聚合与接口测试的实践建议。

2026.11.12

160

15

Go-Zero安装与goctl环境配置教程
Go-Zero安装与goctl环境配置教程

本专题围绕Go-Zero的安装与工具链配置展开,讲清Go版本要求、goctl安装方式、代理镜像、protoc依赖与环境变量设置,说明多版本共存、升级回退与CI流水线安装的做法,并整理安装阶段的常见报错与验证步骤。

2026.11.12

120

15

Go-Zero零基础入门教程
Go-Zero零基础入门教程

本专题整理Go-Zero的入门知识,从框架定位、环境准备到跑通第一个API服务,讲清目录分层、配置加载、日志与中间件的基本用法,并对比Gin、Kratos的差异,帮助Go开发者建立整体认知,判断它是否适合当前项目。

2026.11.12

100

15

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
jQuery官方API文档
jQuery官方API文档

共0课时 | 0人学习

Symfony教程(入门篇+基础篇)
Symfony教程(入门篇+基础篇)

共18课时 | 1.8万人学习