search
HomeBackend DevelopmentPHP TutorialPHP ajax realizes paging without refresh, phpajax refresh paging_PHP tutorial

php ajax implements refresh-free paging, phpajax refreshes paging

This article describes the implementation method of php ajax without refresh paging. Share it with everyone for your reference. The details are as follows:

limit offset, length;
Limit 0,7; First page
Limit 7,7; Second page
Limit 14,7; Page 3
Number of messages per page: 7
Total number of messages: select count(*) from table
Total number of pages of information: ceil rounded up (total number of items/number of items per page)
1. Specific use of paging class

<&#63;php

class Pagination {

  private $total; //数据表中总记录数
  private $listRows; //每页显示行数
  private $limit; //mysql 数据库的limit
  private $uri; //分页信息前面的uri地址
  private $pageNum; //页数
  private $config = array('header' => "个记录", "prev" => "【上一页】", "next" => "【下一页】", "first" => "【首 页】", "last" => "【尾 页】");
  private $listNum = 8;

  /*
   * $total 当前信息总条数
   * $listRows 每页显示的条数
   * $pa 下面的page
    http://网址/index.php&#63;page=5
   */

  public function __construct($total, $listRows = 10, $pa = "") {
    $this->total = $total;
    $this->listRows = $listRows;
    $this->uri = $this->getUri($pa);
    $this->page = !empty($_GET["page"]) &#63; $_GET["page"] : 1;//不传入page,则默认显示首页
    $this->pageNum = ceil($this->total / $this->listRows);
    $this->limit = $this->setLimit();
  }

  //设置每页显示的条数
  private function setLimit() {
    return "Limit " . ($this->page - 1) * $this->listRows . ", {$this->listRows}";
  }

  //获得URL地址
  private function getUri($pa) {
    $url = $_SERVER["REQUEST_URI"] . (strpos($_SERVER["REQUEST_URI"], '&#63;') &#63; '' : "&#63;") . $pa;

    $parse = parse_url($url);



    if (isset($parse["query"])) {
      parse_str($parse['query'], $params);
      unset($params["page"]);
      $url = $parse['path'] . '&#63;' . http_build_query($params);
    }

    return $url;
  }

  //魔术方法,
  public function __get($args) {
    if ($args == "limit")
      return $this->limit;
    else
      return null;
  }

  //页面开始的条数
  private function start() {
    if ($this->total == 0)
      return 0;
    else
      return ($this->page - 1) * $this->listRows + 1;
  }

  //页面结束的条数
  private function end() {
    return min($this->page * $this->listRows, $this->total);
  }

  /*设置首页*/
  private function first() {
    $html = "";
    if ($this->page == 1)
      $html.=' '.$this->config["first"].' ';
    else
      $html.=" <a href='javascript:void(0)' onclick='showPage(\"{$this->uri}&page=1\")'>{$this->config["first"]}</a> ";
      //$html.=" <a href='{$this->uri}&page=1'>{$this->config["first"]}</a> ";

    return $html;
  }

  /*设置上一页*/
  private function prev() {
    $html = "";
    if ($this->page == 1)
      $html.=' '.$this->config["prev"].' ';
    else
      $html.=" <a href='javascript:void(0)' onclick='showPage(\"{$this->uri}&page=" . ($this->page - 1) . "\")'>{$this->config["prev"]}</a> ";
      //$html.=" <a href='{$this->uri}&page=".($this->page-1)."'>{$this->config["prev"]}</a> ";

    return $html;
  }

  //页码列表【首页】【2】【3】…………【尾页】
  private function pageList() {
    $linkPage = "";

    $inum = floor($this->listNum / 2);

    for ($i = $inum; $i >= 1; $i--) {
      $page = $this->page - $i;

      if ($page < 1)
        continue;

      $linkPage.=" <a href='javascript:void(0)' onclick='showPage(\"{$this->uri}&page={$page}\")'>{$page}</a> ";
    }

    $linkPage.=" {$this->page} ";


    for ($i = 1; $i <= $inum; $i++) {
      $page = $this->page + $i;
      if ($page <= $this->pageNum)
        $linkPage.=" <a href='javascript:void(0)' onclick='showPage(\"{$this->uri}&page={$page}\")'>{$page}</a> ";
      else
        break;
    }

    return $linkPage;
  }

  /*设置下一页*/ 
  private function next() {
    $html = "";
    if ($this->page == $this->pageNum)
      $html.=' '.$this->config["next"].' ';
    else
      $html.=" <a href='javascript:void(0)' onclick='showPage(\"{$this->uri}&page=" . ($this->page + 1) . "\")'>{$this->config["next"]}</a> ";
      //$html.=" <a href='{$this->uri}&page=".($this->page + 1)."'>{$this->config["next"]}</a> ";

    return $html;
  }

  /*设置尾页*/
  private function last() {
    $html = "";
    if ($this->page == $this->pageNum)
      $html.=' '.$this->config["last"].' ';
    else
      $html.=" <a href='javascript:void(0)' onclick='showPage(\"{$this->uri}&page=" . ($this->pageNum) . "\")'>{$this->config["last"]}</a> ";
      //$html.=" <a href='{$this->uri}&page=.(this->pageNum).'>{$this->config["last"]}</a> ";

    return $html;
  }

  /*设置页面跳转*/
  private function goPage() {

    return 
    ' <input type="text" onkeydown="javascript:if(event.keyCode==13){var page=(this.value>' . $this->pageNum . ')&#63;' . $this->pageNum . ':this.value;showPage(\'' . $this->uri . '&page=\'+page+\'\')}" value="' . $this->page . '" style="width:25px">
    <input type="button" value="GO" onclick="javascript:var page=(this.previousSibling.value>' . $this->pageNum . ')&#63;' . $this->pageNum . ':this.previousSibling.value;showPage(\'' . $this->uri . '&page=\'+page+\'\')"> ';
  }

  //页面列表配置选项
  function fpage($display = array(0, 1, 2, 3, 4, 5, 6, 7, 8)) {
    $html[0] = " 共有<b>{$this->total}</b>{$this->config["header"]} ";
    $html[1] = " 每页显示<b>" . ($this->end() - $this->start() + 1) . "</b>条,本页<b>{$this->start()}-{$this->end()}</b>条 ";
    $html[2] = " <b>{$this->page}/{$this->pageNum}</b>页 ";

    $html[3] = $this->first();
    $html[4] = $this->prev();
    $html[5] = $this->pageList();
    $html[6] = $this->next();
    $html[7] = $this->last();
    $html[8] = $this->goPage();
    $fpage = '';
    foreach ($display as $index) {
      $fpage.=$html[$index];
    }

    return $fpage;
  }

}

2 Data display

<&#63;php

//链接数据库

//获得具体信息

//分页显示
header("content-type:text/html;charset=utf-8");
$link = mysql_connect('localhost','root','111111');
mysql_select_db('shop', $link);
mysql_query("set names utf8");
$css = <<<eof
<style type="text/css">
  table {border:1px solid black; width:700px; margin:auto; border-collapse:collapse;}
  td {border:1px solid black; }
</style>
eof;
echo $css;

echo "
<table>
  <tr><td>序号</td><td>名称</td><td>数量</td><td>价格</td><td>时间</td></tr>

";

//1 引入分页类
include "./Pagination.php";

//2. 获得信息总条数
$sql = "select * from sw_goods";
$qry = mysql_query($sql);
$total = mysql_num_rows($qry);
$per  = 7;

//3. 实例化分页类对象
$page_obj = new Pagination($total,$per);

//4. 拼装sql语句,获得每页信息
//利用page_obj实现limit的灵活设置
//$page_obj -> limit;
$sqla = "select * from sw_goods ".$page_obj->limit;
$qrya = mysql_query($sqla);

//5. 获得页面列表
$pagelist = $page_obj -> fpage(array(3,4,5,6,7,8));

$i=1;
while($rsta = mysql_fetch_assoc($qrya)){
  echo "<tr>";
  echo "<td>".$i++."</td>";
  echo "<td>".$rsta['goods_name']."</td>";
  echo "<td>".$rsta['goods_number']."</td>";
  echo "<td>".$rsta['goods_price']."</td>";
  echo "<td>".date("Y-m-d H:i:s",$rsta['goods_create_time'])."</td>";
  echo "</tr>";
}
echo "<tr><td colspan=5>".$pagelist."</td></tr>";
echo "</table>";

3 Ajax non-refresh paging implementation

open('get','http://url/index.php?page=2')

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <title>新建网页</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="description" content="" />
    <meta name="keywords" content="" />

    <script type="text/javascript">
//获得分页信息ajax函数
function showPage(myurl){
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function(){
    if(xhr.readyState==4){
      var rst = document.getElementById("result");
      rst.innerHTML = xhr.responseText;
    }
  }
  xhr.open("get",myurl);
  xhr.send(null);
}
window.onload = function(){
  showPage("./data1.php"); //获得分页信息
  //showPage("./data.php&#63;page=2");
}
    </script>

    <style type="text/css">
    </style>
  </head>


  <body>
    <h2 id="ajax无刷新分页效果">ajax无刷新分页效果</h2>
    <div id="result"></div>
  </body>
</html>
<script type="text/javascript">
  document.write(new Date()+"<br />");
  document.write(new Date()+"<br />");
  document.write(new Date()+"<br />");
  document.write(new Date()+"<br />");
</script>

I hope this article will be helpful to everyone’s PHP programming design.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1073128.htmlTechArticlephp ajax realizes refresh-free paging, phpajax refresh paging. This article describes the implementation method of php ajax without refresh paging. Share it with everyone for your reference. The details are as follows: limit offset,...
Statement
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
Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Give an example of how to store a user's name in a PHP session.Give an example of how to store a user's name in a PHP session.Apr 26, 2025 am 12:03 AM

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

See all articles

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools