Home Web Front-end JS Tutorial Ajax implements paging query without refreshing the page

Ajax implements paging query without refreshing the page

Apr 02, 2018 am 10:39 AM
ajax accomplish case

This time I will bring you how to implement paging query without refreshing the page through Ajax. What are the things to note?The following is a practical case. Let’s take a look. one time.

Requirements:

#To obtain a large amount of information in the database and display it on the page, paging queries must be used;

If you don’t use Ajax, but use other methods, you will definitely need to refresh the page, and the user health check will be very bad.

So it is best to use the Ajax method to write paging queries;

1. First find a table with a lot of data!

A simple table

Code, introduce jquery package:

<script src=" jquery-1.11.2.min.js"></script>

Write a table showing our codename and name:

<table class="table table-striped">
 <thead>
 <tr>
 <td>代号</td>
 <td>名称</td>
 <td>操作</td>
 </tr>
 </thead>
 <tbody id="td">
 </tbody>
</table>
Copy after login

These are very simple, Nothing wrong!

2. Set a current page and define a variable as 1 (first page):

 var page = 1;
 //当前页,默认等于1
Copy after login

3. Write the first method below: You need to use ajax. This method mainly functions as a query and paging:

function load()
 {
 $.ajax({
  url: "jiazai.php",
// 显示所有的数据不用写data
  data:{page:page},
//当前页记得传过去
  type:"POST",
  dataType: "TEXT",
  success: function (data) {
  }
 });
 }
Copy after login

4. Write the processing page that displays the data; what needs to be considered here is how many pieces of data to skip and what How many pieces of data you want to display, use limit:

<?php
include ("db.class.php");
$db = new db();
$page=$_POST["page"];
//去当前页page
$num = 3;
//每页显示几条
$tg = ($page-1)*3;//跳过几条
$sql = "select * from min limit {$tg},{$num}";
//limit:两个参数,第一个是跳过多少条,第二个是取多少条
echo $db->Query($sql);
Copy after login

After completing the first step, let’s take a look at the picture:

Display data implementation !

Okay, three pieces of data on each page have been implemented. (I used Bookstrap to beautify the webpage to make the page look like this, as mentioned earlier)

5. Display paging information , write a method, first use ajax to get the total number of pages:

function loadfenye()
 {
 var s = "";
 //用于接收
 var xiao = 1;
// 最大页
 var da = 1;
// 最小页
 $.ajax({
 async:false,
//  做成同步
 url:"zys.php",
 dataType:"TEXT",
 success:function(data){
 da = data;
 //最大页数
  }
});
 }
Copy after login

Next, do the php page to query the total number of pages:

<?php
//查询总页数
include ("db.class.php");
$db = new db();
$sql = "select count(*) from min";
$zts = $db->strquery($sql);
//总条数
echo ceil($zts/3);
//ceil向上取整
Copy after login

Okay, the total number of pages is obtained , come back and finish writing the pagination:

//加载分页信息方法
 function loadfenye()
 {
  var s = "";
  //用于接收
  var xiao = 1;
//  最大页
  var da = 1;
//  最小页
  $.ajax({
 async:false,
//   做成同步
 url:"zys.php",
 dataType:"TEXT",
 success:function(data){
  da = data;
  //最大页数,查到的最大页数交个默认的最大页数
   }
});
//加载上一页
  s += "<li><a>«</a></li>";
//  加载分页列表
for(i=page-4;i<page+5;i++)
{
 //i代表列表的页数
 if(i>=xiao && i<=da)
 {
  s += " <li><a>"+i+"</a></li>"
 }
}
  //  加载下一页
  s += "<li><a>»</a></li>";
$("#fenye").html(s);
 }
Copy after login

After writing this, look at the picture:

The pagination information is also displayed

6. Let’s change the background color of the default selected page

Take a look at Bookstrap; how to change the background color:

Obviously there is an additional active style, let’s add it using judgment

if(i>=xiao && i<=da) {
  if (i == page) {
   s += " <li class=&#39;active&#39;><a>" + i + "</a></li>"
  }
  else {
   s += " <li><a>" + i + "</a></li>";
  }
Copy after login

Okay, take a look:

Yes, no problem

7. Create a click event on the page number to jump to the page number and display the data, and update the list;

First add a class

s += " <li class='active list'><a>" + i + "</a></li&gt ;"

Then write the method:

//给列表加上点击事件
  $(".list").click(function(){
   //改变当前页数
   //把点击的页数,扔给page(当前页)
   page = $(this).text();
//   page获取了当前页,重新加载以下方法
   //调用load方法
   load();
   //把加载数据封装成一个方法
   loadfenye();
   //加载分页信息方法
  })
 }
Copy after login

When I click on the fifth page:

Nothing wrong;

8. Next is the click event on the previous page and the next page. The first is the click event on the previous page:

First add class to the list on the previous page , easy to write events:

s += "<li class='sy'><a>«</a></li>";

Come on, the click event on the previous page:

$(".sy").click(function(){
   //改变当前页
   if(page>1)
   {
    //如果不是第一页
    page = parseInt(page) - 1;
   }
   //   page获取了当前页,重新加载以下方法
   //调用load方法
   load();
   //把加载数据封装成一个方法
   loadfenye();
   //加载分页信息方法
  })
Copy after login

The click event on the next page:

Same as above: add class to the list to facilitate writing events:

s += "<li class=&#39;xy&#39;><a>»</a></li>"; 

下一页点击事件:

//下一页点击事件
  $(".xy").click(function(){
//   alert(da);
   if(page<da)
   {
    //如果不是第一页
    page = parseInt(page) + 1;
   }
   //   page获取了当前页,重新加载以下方法
   //调用load方法
   load();
   //把加载数据封装成一个方法
   loadfenye();
   //加载分页信息方法
  })
Copy after login

好,完美实现ajax分页查询;

8.再加一个按条件查询:

加上文本框:

<p>
 <input type="text" id="name"/>
 <input type="button" id="chaxun" value="查询"/>
</p>
Copy after login

来写点击事件:

//给查询加点击事件
 $("#chaxun").click(function(){
  //重新加载
  //调用load方法
  load();
  //把加载数据封装成一个方法
  loadfenye();
  //加载分页信息方法
 })
Copy after login

接下来我们需要改一下这两个方法:

ajax只需要把文本框的name传过去就好啦:

data:{page:page,name:name},
   type:"POST",
Copy after login
data:{name:name},
 type:"POST",
Copy after login

在处理页面,设置一个恒等的条件:

$tj = " 1=1 ";
if(!empty($_POST["name"]))
{
 $name = $_POST["name"];
 $tj = " name like '%{$name}%' ";
}
Copy after login

最后在sql语句后面调用就好啦

图:

页面不刷新的分页查询就欧克了;

源码:

显示页面:




 
 无标题文档
 
 
 



显示数据

<p>  <input type="text" id="name"/>  <input type="button" id="chaxun" value="查询"/> </p>
                    
代号名称操作

     

   

          

 

<script>  var page = 1;  //当前页,默认等于1  //调用load方法  load();  //把加载数据封装成一个方法  loadfenye();  //加载分页信息方法  //给查询加点击事件  $(&quot;#chaxun&quot;).click(function(){   //重新加载   //调用load方法   load();   //把加载数据封装成一个方法   loadfenye();   //加载分页信息方法  })  function loadfenye()  {   var s = "";   //用于接收   var name = $("#name").val();   var xiao = 1; //  最大页   var da = 1; //  最小页   $.ajax({  async:false, //   做成同步  url:"zys.php",  data:{name:name},  type:&quot;POST&quot;,  dataType:"TEXT",  success:function(data){   da = data;   //最大页数    } }); //加载上一页   s += "<li class=&#39;sy&#39;><a>«</a></li>"; //  加载分页列表 for(var i=page-4;i<page+5;i++) { //i代表列表的页数 if(i>=xiao && i<=da) { if (i == page) { s += " <li class=&#39;active list&#39;><a>" + i + "</a></li>"   }   else {    s += " <li class=&#39;list&#39;><a>" + i + "</a></li>";   }  } }   //  加载下一页   s += "<li class=&#39;xy&#39;><a>»</a></li>"; $("#fenye").html(s); //给列表加上点击事件   $(".list").click(function(){    //改变当前页数    //把点击的页数,扔给page(当前页)    page = $(this).text(); //   page获取了当前页,重新加载以下方法    //调用load方法    load();    //把加载数据封装成一个方法    loadfenye();    //加载分页信息方法   })   //上一页点击事件   $(&quot;.sy&quot;).click(function(){    //改变当前页    if(page&gt;1)    {     //如果不是第一页     page = parseInt(page) - 1;    }    //   page获取了当前页,重新加载以下方法    //调用load方法    load();    //把加载数据封装成一个方法    loadfenye();    //加载分页信息方法   })   //下一页点击事件   $(".xy").click(function(){ //   alert(da);    if(page<da)    {     //如果不是第一页     page = parseInt(page) + 1;    }    //   page获取了当前页,重新加载以下方法    //调用load方法    load();    //把加载数据封装成一个方法    loadfenye();    //加载分页信息方法   })  }  function load()  {   var name = $("#name").val();   $.ajax({    url: "jiazai.php", //  显示所有的数据不用写data    data:{page:page,name:name},    type:&quot;POST&quot;,    dataType: "TEXT",    success: function (data) {     var str = "";     var hang = data.split("|");     //split拆分字符串     for (var i = 0; i < hang.length; i++) {      //通过循环取到每一行;拆分出列;      var lie = hang[i].split("-");      str = str +       "<tr><td>"       + lie[0] +       "</td><td>"       + lie[1] +       "</td><td>" +       "<button type=&#39;button&#39; class=&#39;btn btn-info sc&#39; ids=&#39;"+lie[0]+"&#39;>点击删除</button><button type=&#39;button&#39; class=&#39;btn btn-primary xq&#39; ids=&#39;"+lie[0]+"&#39;>查看详情</button>" +       //ids里面存上主键值       "</td></tr>";     }     $("#td").html(str);     //找到td把html代码扔进去     addshanchu();     addxiangqing();    }   });  }  //给查看详情加事件  function addxiangqing()  {   $(".xq").click(function(){    $('#myModal').modal('show')    //打开模态框    var ids = $(this).attr("ids");    $.ajax({     url:"xiangqing.php",     data:{ids:ids},     dataType:"TEXT",     type:"POST",      success:function(data){      //拆分       var lie = data.split("^"); //      var str = "<p>代号:"+lie[0]+"</p><p>名称:"+lie[1]"</p>";       //造字符串       var str = "<p>代号:"+lie[0]+"</p><p>名称:"+lie[1]+"</p>";       $("#nr").html(str);    }    });    //在模态框里面要显示的内容   })  }  //把删除事件封装成方法:  function addshanchu()  {   //给删除按钮加上事件   $(".sc").click(function () {    var ids = $(this).attr("ids");    $.ajax({     url: "shanchu.php",     data: {ids: ids},     dataType: "TEXT",     type: "POST",     success: function (d) {      if (d.trim() == "ok") {       alert("删除成功");       //调用加载数据的方法       load();      }      else {       alert("删除失败");      }     }    });   })  } </script>
Copy after login

查询总页数的页面:

<?php
//查询总页数
include ("db.class.php");
$db = new db();
$tj = " 1=1 ";
if(!empty($_POST["name"]))
{
 $name = $_POST["name"];
 $tj = " name like &#39;%{$name}%&#39; ";
}
$sql = "select count(*) from min WHERE {$tj} ";
$zts = $db->strquery($sql);
//总条数
echo ceil($zts/3);
//ceil向上取整
Copy after login

加载分页信息的页面:

<?php
include ("db.class.php");
$db = new db();
$page=$_POST["page"];
//去当前页page
$tj = " 1=1 ";
if(!empty($_POST["name"]))
{
 $name = $_POST["name"];
 $tj = " name like &#39;%{$name}%&#39; ";
}
$num = 3;
//每页显示几条
$tg = ($page-1)*3;//跳过几条
$sql = "select * from min where {$tj} limit {$tg},{$num}";
//limit:两个参数,第一个是跳过多少条,第二个是取多少条
$arr = $db->Query($sql);
//遍历
$str="";
foreach ($arr as $v)
{
 $str = $str.implode("-",$v)."|";
 //用-把$v拼起来,拼出来是1-红2-蓝,用|分割,拼出来是1-红|2-蓝|
}
$str = substr($str,0,strlen($str)-1);
//截取字符串:从第0个开始,截取它的长度-1
//strlen获取字符串长度
echo $str;
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

如何给使用Ajax返回的标签动态添加样式

ajax的校验功能怎样用SSM整合框架实现

The above is the detailed content of Ajax implements paging query without refreshing the page. 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)

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to implement exact division operation in Golang How to implement exact division operation in Golang Feb 20, 2024 pm 10:51 PM

Implementing exact division operations in Golang is a common need, especially in scenarios involving financial calculations or other scenarios that require high-precision calculations. Golang's built-in division operator "/" is calculated for floating point numbers, and sometimes there is a problem of precision loss. In order to solve this problem, we can use third-party libraries or custom functions to implement exact division operations. A common approach is to use the Rat type from the math/big package, which provides a representation of fractions and can be used to implement exact division operations.

Master how Golang enables game development possibilities Master how Golang enables game development possibilities Mar 16, 2024 pm 12:57 PM

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

PHP Game Requirements Implementation Guide PHP Game Requirements Implementation Guide Mar 11, 2024 am 08:45 AM

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

See all articles