Table of Contents
Foreword
thinkphp ajax paging class
Specific steps
1. Controller part
2. Template part
3.js part
Summary
Home PHP Framework ThinkPHP Teach you step by step how to implement thinkphp ajax pagination without refresh

Teach you step by step how to implement thinkphp ajax pagination without refresh

Sep 20, 2021 pm 04:59 PM
ajax jquery php thinkphp

The followingthinkphp frameworkThe tutorial column will introduce to you how to implement thinkphp's ajax non-refresh paging. I hope it will be helpful to friends in need!

Foreword

The paging class that comes with the thinkphp framework is to turn pages every time The entire page has to be refreshed. This kind of page-turning user experience is obviously not ideal. We hope that each time we turn the page, we only refresh the data in the part of the data set we want. In this way, we can easily think of ajax asynchronous communication, using ajax Asynchronously interact with the database (I use mysql database during the development process), return the data queried from the database, replace the original data with jquery, and perform partial refresh without refreshing the page, thus achieving our expectations Effect.

thinkphp ajax paging class

This paging class is a resource found on the Internet. You can create such a class directly in your own thinkphp. My class name here is AjaxPage.class.php

<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Page.class.php 2712 2012-02-06 10:12:49Z liu21st $
namespace Common\Common;
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 class=&#39;ajaxify&#39; id=&#39;big&#39; href=&#39;JavaScript:".$this->ajax_func."(".$upRow.")'>".$this->config['prev']."</a>";
        }else{
            $upPage="";
        }

        if ($downRow <= $this->totalPages){
            $downPage="<a class=&#39;ajaxify&#39; id=&#39;big&#39; href=&#39;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=&#39;ajaxify&#39; id=&#39;big&#39; href=&#39;javascript:".$this->ajax_func."(".$preRow.")'>上".$this->rollPage."页</a>";
            $theFirst = "<a class=&#39;ajaxify&#39; id=&#39;big&#39; href=&#39;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=&#39;ajaxify&#39; id=&#39;big&#39; href=&#39;javascript:".$this->ajax_func."(".$nextRow.")' >下".$this->rollPage."页</a>";
            $theEnd = "<a class=&#39;ajaxify&#39; id=&#39;big&#39; href=&#39;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=&#39;ajaxify&#39; id=&#39;big&#39; href=&#39;javascript:".$this->ajax_func."(".$page.")'> ".$page." </a>";
                }else{
                    break;
                }
            }else{
                if($this->totalPages != 1){
                    $linkPage .= " <span class=&#39;current&#39;>".$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;
    }

}

?>
Copy after login

Specific steps

Next, we will implement the thinkphp non-refresh paging effect step by step starting from the controller.

1. Controller part

This is just the core code of a part of the controller.

        //实例化数据模型
        $info=M('info');
        //统计要查询数据的数量
        $count=$info->where("ID='$id'")->count();
        //实例化分页类,传入三个参数,分别是数据总数、每页显示的数据条数、要调用的jQuery ajax方法名
        $p=new \Host\Common\AjaxPage($count,10,'server');
        //产生分页信息
        $page=$p->show();
        //要查询的数据,limit表示每页查询的数量,这里为10条
        $data = $server_info->where("ID='$id'")->limit($p->firstRow.','.$p->listRows)->select();
        //assign方法往模板赋值
        $this->assign('list',$data);
        $this->assign('page',$page);
        //ajax返回信息
        $res["content"] = $this->fetch('Index/myinfolist')
        $this->ajaxReturn($res);
Copy after login

2. Template part

The template name: myinfolist.html is consistent with the template rendered in the controller above.

 $res["content"] = $this->fetch('Index/myinfolist')
Copy after login

Because the front-end uses the bootstrap framework, many classes in this template are from bootstrap. You don’t need to worry too much about this. Just look at the key points of the whole process.

<!DOCTYPE html>
<head>
</head>
    <p id="server">
        <p class="row-fluid"  >
            <p class="span12">
                <p class="portlet box green">
                    <p class="portlet-title">
                        <p class="caption"><i class="icon-globe"></i>信息列表</p>
                    </p>

                    <p class="portlet-body" >
                
                        <table class="table table-striped table-bordered table-hover table-full-width" id="sample_1">

                            <thead>

                                <tr>
                                    <th class="hidden-480">a</th>
                                    <th class="hidden-480">b</th>
                                    <th class="hidden-480">c</th>
                                    <th class="hidden-480">d</th>
                                </tr>

                            </thead>

                            <tbody>
                                    //循环赋值
                                    <foreach name=&#39;list&#39; item=&#39;info&#39;>
                                        <tr>
                                            <td>{$info.a}</td>
                                            <td>{$info.b}</td>     
                                            <td>{$info.c}</td>
                                            <td>{$info.d}</td>
                                         
                                        </tr>
                                    </foreach>
                                
                            </tbody>
                            
                        </table>
                        //分页信息
                        <p class="row-fluid"> {$page} </p>
                        
                    </p>
                </p>    
            </p>        
        </p>
    </p>
    
    <script src="__PUBLIC__/server.js"></script> 
</html>
Copy after login

3.js part

This step is the focus of realizing ajax non-refresh paging. It uses jQuery’s ajax communication and writes the obtained data to the template through ajax interaction with the database. , replace the previous data set to achieve the purpose of paging.
server.js

function server(id){  
         var id = id;
            $.get('/Server/myinfo', {'p':id}, function(data){  
            //用get方法发送信息到Server中的myinfo方法
             $("#server").replaceWith("<p  id=&#39;user7&#39;>"
             +data.content+
             "</p>"); 
        });
    }
Copy after login

This method name server is the third parameter passed in the instantiated paging class in the controller. Every time you click on the template to turn the page, this js method server (p ), which page number is passed.

$p=new \Host\Common\AjaxPage($count,10,'server');
Copy after login

What is used here is the .get form of the ajax method in jQuery to communicate between ajax and the background. To get the returned data, use the replaceWith method, and use

<p  id=&#39;user7&#39;>+数据</p>
Copy after login

to replace the id of server in the template. p, to achieve paging effect.

Summary

The above steps are the specific steps to implement ajax paging. jQuery’s ajax methods include $.ajax, $.get, and $.post. I will not introduce them here. The code In my program, in order not to expose some of my data fields, I replaced them with abcd and made certain deletions. If there are any problems, I hope everyone can correct me and communicate with me.

The above is the detailed content of Teach you step by step how to implement thinkphp ajax pagination without refresh. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

ThinkPHP6 routing: How to completely obtain URL parameters containing special characters such as Chinese? ThinkPHP6 routing: How to completely obtain URL parameters containing special characters such as Chinese? Apr 01, 2025 pm 02:51 PM

ThinkPHP6 routing parameters are processed in Chinese and complete acquisition. In the ThinkPHP6 framework, URL parameters containing special characters (such as Chinese and punctuation marks) are often processed...

See all articles