Home Web Front-end JS Tutorial How to implement Ajax paging without refreshing

How to implement Ajax paging without refreshing

Apr 04, 2018 pm 01:37 PM
ajax Pagination

This time I will show you how to implement Ajax paging without refreshing, and what are the precautions to implement Ajax paging without refreshing. The following is a practical case, let's take a look.

Following the previous article - Java+Oracle code to implement paging (2) on the principles and implementation of paging technology, this article continues to analyze paging technology. The previous article talked about the code implementation of paging technology. This article continues to analyze the effect control of paging technology.

In the previous article, we have simply implemented a paging using code. But we have all seen that every time the result set is obtained through the servlet request in the code, it will be redirected to a jsp page to display the results, so that the page will be refreshed every time the query appears. For example, after querying the result set and looking at the third page, the page will be Will refresh it. The effect of this page will be a bit uncomfortable, so we hope that no matter which page is accessed after querying the result set through conditions, the page will not be refreshed, but only the result set will change. To solve this, I think everyone will easily think of Ajax.
Yes, we have to ask Ajax to come out. After the result set is queried through the query conditions, every subsequent visit to any page will be accessed through Ajax. Asynchronous Ajax is used to interact with the Servlet, and the results are queried and returned to Ajax. In this way, the page content changes because Ajax returns the results, and The page will not be refreshed, which implements refresh-free paging technology.
Let’s take a look at a simple non-refresh paging implementation. The code is as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <link rel="stylesheet" href="../lib/jquery_pagination/pagination.css" mce_href="lib/jquery_pagination/pagination.css" />
 <mce:script type="text/<a href="http://lib.csdn.net/base/javascript" class=&#39;replace_word&#39; title="JavaScript知识库" target=&#39;_blank&#39; style=&#39;color:#df3434; font-weight:bold;&#39;>JavaScript</a>" src="../lib/<a href="http://lib.csdn.net/base/jquery" class=&#39;replace_word&#39; title="jQuery知识库" target=&#39;_blank&#39; style=&#39;color:#df3434; font-weight:bold;&#39;>jQuery</a>/jquery.min.js" mce_src="lib/jquery/jquery.min.js"></mce:script>
 <mce:script type="text/javascript"
  src="../lib/jquery_pagination/jquery.pagination.js"></mce:script>
 <mce:script type="text/javascript"><!--
 /**
 * Callback function that displays the content.
 *
 * Gets called every time the user clicks on a pagination link.
 *
 * @param {int}page_index New Page index
 * @param {jQuery} jq the <a href="http://lib.csdn.net/base/docker" class=&#39;replace_word&#39; title="Docker知识库" target=&#39;_blank&#39; style=&#39;color:#df3434; font-weight:bold;&#39;>Container</a> with the pagination links as a jQuery object
 */
 function pageselectCallback(page_index, jq) {
 var new_content = $('#hiddenresult p.result:eq(' + page_index + ')')
  .clone();
 $('#Searchresult').empty().append(new_content);
 return false;
 }
 function initPagination() {
 var num_entries = $('#hiddenresult p.result').length;
 // Create pagination element
 $("#Pagination").pagination(num_entries, {
  num_edge_entries : 2,
  num_display_entries : 8,
  callback : pageselectCallback,
  items_per_page : 1
 });
 }
 // When the HTML has loaded, call initPagination to paginate the elements    
 $(document).ready(function() {
 initPagination();
 });
// --></mce:script>
 <mce:style type="text/css"><!--
* {
 padding: 0;
 margin: 0;
}
body {
 background-color: #fff;
 margin: 20px;
 padding: 0;
 height: 100%;
 font-family: Arial, Helvetica, sans-serif;
}
#Searchresult {
 margin-top: 15px;
 margin-bottom: 15px;
 border: solid 1px #eef;
 padding: 5px;
 background: #eef;
 width: 40%;
}
#Searchresult p {
 margin-bottom: 1.4em;
}
--></mce:style><style type="text/css" mce_bogus="1">* {
 padding: 0;
 margin: 0;
}
body {
 background-color: #fff;
 margin: 20px;
 padding: 0;
 height: 100%;
 font-family: Arial, Helvetica, sans-serif;
}
#Searchresult {
 margin-top: 15px;
 margin-bottom: 15px;
 border: solid 1px #eef;
 padding: 5px;
 background: #eef;
 width: 40%;
}
#Searchresult p {
 margin-bottom: 1.4em;
}</style>
 <title>Pagination</title>
 </head>
 <body>
 <h4>
  jQuery Pagination Plugin Demo
 </h4>
 <p id="Pagination" class="pagination">
 </p>
 <br style="clear: both;" mce_style="clear: both;" />
 <p id="Searchresult">
  This content will be replaced when pagination inits.
 </p>
 <p id="hiddenresult" style="display: none;" mce_style="display: none;">
  <p class="result">
  <p>
   Globally maximize granular "outside the box" thinking vis-a-vis
   quality niches. Proactively formulate 24/7 results whereas 2.0
   catalysts for change. Professionally implement 24/365 niches rather
   than client-focused users.
  </p>
  <p>
   Competently engineer high-payoff "outside the box" thinking through
   cross functional benefits. Proactively transition intermandated
   processes through open-source niches. Progressively engage
   maintainable innovation and extensible interfaces.
  </p>
  </p>
  <p class="result">
  <p>
   Credibly fabricate e-business models for end-to-end niches.
   Compellingly disseminate integrated e-markets without ubiquitous
   services. Credibly create equity invested channels with
   multidisciplinary human capital.
  </p>
  <p>
   Interactively integrate competitive users rather than fully tested
   infomediaries. Seamlessly initiate premium functionalities rather
   than impactful architectures. Rapidiously leverage existing
   resource-leveling processes via user-centric portals.
  </p>
  </p>
  <p class="result">
  <p>
   Monotonectally initiate unique e-services vis-a-vis client-centric
   deliverables. Quickly impact parallel opportunities with B2B
   bandwidth. Synergistically streamline client-focused
   infrastructures rather than B2C e-commerce.
  </p>
  <p>
   Phosfluorescently fabricate 24/365 e-business through 24/365 total
   linkage. Completely facilitate high-quality systems without
   stand-alone strategic theme areas.
  </p>
  </p>
 </p>
 </body>
</html>
Copy after login
This is a very simple non-refresh paging implementation, using the JQuery+ jquery.pagination framework. Now with the popularity of frameworks, especially the popularity of Jquery, it is very effective to use frameworks for development. The above code principle has been commented in the code. You can also refer to Jquery's official website:.

Now we can develop our Ajax non-refresh paging implementation. Based on the above principle, in pageselectCallback() in the code that responds to the page number being pressed, we use an Ajax to asynchronously access the database, take out the result set through the clicked page number, and then set it to the page asynchronously, so that no refresh can be completed accomplish.

The response function pageselectCallback() when the page number is pressed is modified as follows:

In this way, the results can be obtained asynchronously and the showResponse function is used to process the results. The showResponse function is as follows:

function showResponse(request){
   var content = request;
   var root = content.documentElement;
   var responseNodes = root.getElementsByTagName("root");
   var itemList = new Array();
   var pageList=new Array();
   alert(responseNodes.length);
   if (responseNodes.length > 0) {
    var responseNode = responseNodes[0];
    var itemNodes = responseNode.getElementsByTagName("data");
    for (var i=0; i<itemNodes.length; i++) {
     var idNodes = itemNodes[i].getElementsByTagName("id");
     var nameNodes = itemNodes[i].getElementsByTagName("name");
     var sexNodes=itemNodes[i].getElementsByTagName("sex");
     var ageNodes=itemNodes[i].getElementsByTagName("age");
     if (idNodes.length > 0 && nameNodes.length > 0&&sexNodes.length > 0&& ageNodes.length > 0) {
      var id=idNodes[0].firstChild.nodeValue;
      var name = nameNodes[0].firstChild.nodeValue;
      var sex = sexNodes[0].firstChild.nodeValue;
      var age=ageNodes[0].firstChild.nodeValue;
      itemList.push(new Array(id,name, sex,age));
     }
    }
    
    var pageNodes = responseNode.getElementsByTagName("pagination");
    if (pageNodes.length>0) {
     var totalNodes = pageNodes[0].getElementsByTagName("total");
     var startNodes = pageNodes[0].getElementsByTagName("start");
     var endNodes=pageNodes[0].getElementsByTagName("end");
     var currentNodes=pageNodes[0].getElementsByTagName("pageno");
     if (totalNodes.length > 0 && startNodes.length > 0&&endNodes.length > 0) {
      var total=totalNodes[0].firstChild.nodeValue;
      var start = startNodes[0].firstChild.nodeValue;
      var end = endNodes[0].firstChild.nodeValue;
      var current=currentNodes[0].firstChild.nodeValue;
      pageList.push(new Array(total,start,end,current));
     }
    }
   }
   showTable(itemList,pageList);
  }
Copy after login
The above code is used to process the results in XML format returned after asynchronously requesting the Servlet through Ajax. The Servlet code is in the previous article. Among them, itemList and pageList are the user List and paging navigation generated after parsing and returning respectively, so that users can display data in their own way.

function pageselectCallback(page_index, jq){
  var pars="pageNo="+(page_index+1);
   $.ajax({
    type: "POST",
   url: " UserBasicSearchServlet",
   cache: false,
   data: pars,
   success: showResponse
  });
    return false;
}
Copy after login
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How does AjaxToolKit use the Rating control

How does jQuery+ajax implement json data traversal

The above is the detailed content of How to implement Ajax paging without refreshing. 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 solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

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 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

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

Detailed explanation of the principle of MyBatis paging plug-in Detailed explanation of the principle of MyBatis paging plug-in Feb 22, 2024 pm 03:42 PM

MyBatis is an excellent persistence layer framework. It supports database operations based on XML and annotations. It is simple and easy to use. It also provides a rich plug-in mechanism. Among them, the paging plug-in is one of the more frequently used plug-ins. This article will delve into the principles of the MyBatis paging plug-in and illustrate it with specific code examples. 1. Paging plug-in principle MyBatis itself does not provide native paging function, but you can use plug-ins to implement paging queries. The principle of paging plug-in is mainly to intercept MyBatis

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

Best way to implement array pagination in PHP Best way to implement array pagination in PHP May 04, 2024 pm 02:39 PM

There are two most common ways to paginate PHP arrays: using the array_slice() function: calculate the number of elements to skip, and then extract the specified range of elements. Use built-in iterators: implement the Iterator interface, and the rewind(), key(), current(), next(), and valid() methods are used to traverse elements within the specified range.

See all articles