jQuery+Ajax to achieve simple paging effect

jQuery+Ajax to achieve simple paging effect

This article shares the specific code of jquery+Ajax to achieve the paging effect for your reference. The specific content is as follows

1. If it is a jsp page, you can use EL expressions and JSTL tags to create a paging strip, which is not difficult. The disadvantage of using EL expressions and JSTL tags is that asynchronous effects cannot be achieved, and the entire page is refreshed.

Second, if it is a normal HTML page, of course, you cannot use EL expressions and JSTL tags. At this time, you can only implement it through asynchronous Ajax. Of course, both methods can be used for JSP pages.

3. Pagination bar, here I use Ajax and Jquery to do it. The implementation is rather complicated and the code is very long because it involves concatenating a bunch of strings and then using the html() method or the append() method to change the content of the document.

4. Pre-Analysis

There are two parameters that the browser needs to send to the server:

①The current page number currentPage;
②Page size (how many records are displayed on one page) pageSize.

The server sends data in Json format to the browser, which is a page entity class PageBean. The PageBean has the following fields:

①Total number of records totalCount;
②Total page number totalPage;
③List list of data on each page;
④Current page number currentPage;
⑤The number of records displayed per page: pageSize.

This PageBean supports generics, the code is as follows:

public class PageBean<T> 
{
    private int totalCount; // Total number of recordsprivate int totalPage ; // Total page numbersprivate List<T> list ; // Data per pageprivate int currentPage ; // Current page numberprivate int rows;//Number of records displayed per page, that is, pageSize

    public int getTotalCount() 
    {
        return totalCount;
    }

    public void setTotalCount(int totalCount)
    {
        this.totalCount = totalCount;
    }

    public int getTotalPage() 
    {
        return totalPage;
    }

    public void setTotalPage(int totalPage) 
    {
        this.totalPage = totalPage;
    }

    public List<T> getList() 
    {
        return list;
    }

    public void setList(List<T> list) 
    {
        this.list = list;
    }

    public int getCurrentPage() 
    {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) 
    {
        this.currentPage = currentPage;
    }

    public int getRows() 
    {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    @Override
    public String toString() 
    {
        return "PageBean{" +
                "totalCount=" + totalCount +
                ", totalPage=" + totalPage +
                ", list=" + list +
                ", currentPage=" + currentPage +
                ", rows=" + rows +
                '}';
    }
}

To achieve paging, you must use the "limit" in the SQL statement. Let me give you an example to illustrate the meaning.

select * from student limit 2,5;

Specific meaning: Query data from the student table, starting from the record with index "2", and querying 5 records thereafter.

The index starts at 0, so the above statement is equivalent to querying the 3rd, 4th, 5th, 6th, and 7th records, a total of 5 records.

In short, the first number means "where to start searching", and the second number means "how many entries to search further".

The “where to start searching” here needs to be calculated. The formula is as follows:

(currentPage-1)×pageSize

That is, the current page number minus one, in parentheses, and then multiplied by the page size.

So the pseudo code of the query statement is as follows:

select * from student limit (currentPage-1)×pageSize,pageSize;

The total page number totalPage can be calculated by the total number of records totalCount and the page size pageSize. The code is as follows:

totalPage=totalCount%pageSize==0?totalCount/pageSize:(totalCount/pageSize+1);

5. Main code on the server side

import com.fasterxml.jackson.databind.ObjectMapper;
import domain.PageBean;
import domain.RainFall;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import util.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/ViewRainByPageServlet")
public class ViewRainByPageServlet extends HttpServlet
{
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        JdbcTemplate template = new JdbcTemplate (JDBCUtils.getDataSource());
        String sql="select * from rain_fall limit ?,?";//Query some tuples String sql2="select * from rain_fall";//Query all tuples List<RainFall> countList = template.query(sql2, new BeanPropertyRowMapper<RainFall>(RainFall.class));
        int totalCount = countList.size(); //Get the total number of records from the database int totalPage; //First declare the total page number, which needs to be calculated based on the data sent by the client String currentPage = request.getParameter("currentPage");
        String pageSize = request.getParameter("pageSize");
        int intCurrentPage = Integer.parseInt(currentPage); //The current page number sent by the user if (intCurrentPage==0) //When the user clicks the previous page button, currentPage will be reduced by 1, and it may be reduced to 0 {
            intCurrentPage=1; //If the user's currentPage=0, directly set the page number to 1 and return the first page of data to the client}

        int intPageSize = Integer.parseInt(pageSize); //page size sent by user totalPage = totalCount% intPageSize == 0? totalCount / intPageSize: (totalCount / intPageSize + 1); //calculate the total number of pages if (intCurrentPage > totalPage) //user clicks the next page button, currentPage will increase by 1, which may be greater than the total number of pages {
            intCurrentPage=totalPage; //Set the current page number to the total number of pages}

        int startIndex=(intCurrentPage-1)*intPageSize; //From which record index should the query begin?

        List<RainFall> list = template.query(sql, new BeanPropertyRowMapper<RainFall>(RainFall.class),startIndex,intPageSize);
        ObjectMapper mapper=new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");//Set the response data type and character encoding PageBean<RainFall> pageBean=new PageBean<>();//Create PageBean object//Encapsulate PageBean object pageBean.setTotalCount(totalCount);
        pageBean.setTotalPage(totalPage);
        pageBean.setList(list);
        pageBean.setCurrentPage(intCurrentPage);
        pageBean.setRows(intPageSize);
        //Write data back to the client System.out.println(pageBean);
        mapper.writeValue(response.getOutputStream(),pageBean);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {

        this.doPost(request, response);

    }
}

6. Front-end code (very long)

<%--
  Created by Yingyong Lao.
  User: laoyingyong
  Date: 2019-12-10
  Time: 19:28
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>View rainfall information</title>
    <!-- 1. Import CSS global styles -->
    <link href="css/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- 2. jQuery import, it is recommended to use version 1.9 or above -->
    <script src="js/jquery-2.1.0.min.js"></script>
    <!-- 3. Import bootstrap's js file-->
    <script src="js/bootstrap.min.js"></script>
    <script>
        $(function () //Entry function {
            $.post("ViewRainByPageServlet",{currentPage:1,pageSize:5},function (data)//After the page is loaded, send an ajax request to request the first 5 records and complete the initialization of the interface {
               var totalCount=data.totalCount;//Total number of recordsvar totalPage=data.totalPage;//Total number of pagesvar currentPage=data.currentPage;//Current page numberif(currentPage==1)//If the current page number is 1 and the user clicks on the previous page, set class="disabled" to display a "disabled" icon{
                    var str = ' <li class="disabled" onclick="findByPage('+(currentPage-1)+',5)">\n' +
                        ' <a href="#" aria-label="Previous">\n' +
                        ' <span aria-hidden="true">&laquo;</span>\n' +
                        ' </a>\n' +
                        ' </li>';

                }
                else //Otherwise the button on the previous page is in normal style {
                    var str=' <li οnclick="findByPage('+(currentPage-1)+',5)">\n' +
                        ' <a href="#" aria-label="Previous">\n' +
                        ' <span aria-hidden="true">&laquo;</span>\n' +
                        ' </a>\n' +
                        ' </li>';

                }

                for(var i=1;i<=totalPage;i++)//Traverse the page number, which is the number between the two icons (previous page and next page) {
                    if(i==currentPage)//If the current number is equal to the current page number currentPage, set class="active", that is, the page number is highlighted {
                        var item='<li οnclick="findByPage('+i+',5);" class="active"><a href="#">'+i+'</a></li>';
                    }
                    else
                    {
                        var item='<li οnclick="findByPage('+i+',5);"><a href="#">'+i+'</a></li>';
                    }
                    str=str+item;

                }
                if(currentPage==totalPage)//If the current page number is the last page and the user clicks on the next page, set class="disabled" so that a "disabled" icon appears {
                    var strend='<li class="disabled" onclick="findByPage('+(currentPage+1)+',5)">\n' +
                        ' <a href="#" aria-label="Next">\n' +
                        ' <span aria-hidden="true">&raquo;</span>\n' +
                        ' </a>\n' +
                        ' </li>\n' +
                        ' <span style="font-size: 24px" id="total_sp">Total '+totalCount+' records, total '+totalPage+' pages</span>';

                }
                else //If it is not the last page, it is the normal style {
                    var strend='<li οnclick="findByPage('+(currentPage+1)+',5)">\n' +
                        ' <a href="#" aria-label="Next">\n' +
                        ' <span aria-hidden="true">&raquo;</span>\n' +
                        ' </a>\n' +
                        ' </li>\n' +
                        ' <span style="font-size: 24px" id="total_sp">Total '+totalCount+' records, total '+totalPage+' pages</span>';

                }

                str=str+strend;
                $("#fenyelan").html(str); //Pagination bar initialization var array=data.list;
                for(var i=0;i<array.length;i++)
                {
                    var obj=array[i];
                    var id=obj.id;
                    var area=obj.area;
                    var precipitation = obj.precipitation;
                    var month=obj.month;
                    var releaseDate=obj.releaseDate;
                    // Initialization of the table $("#rain_table").append('<tr class="info">\n' +
                        ' <td style="text-align: center">'+id+'</td>\n' +
                        ' <td style="text-align: center">'+area+'</td>\n' +
                        ' <td style="text-align: center">'+precipitation+'</td>\n' +
                        ' <td style="text-align: center">'+month+'</td>\n' +
                        ' <td style="text-align: center">'+releaseDate+'</td>\n' +
                        ' </tr>');
                }

            });//Send ajax request after the page is loaded end

        });//Entry function end



        //The page button click callback function does not need to be written in the entry function, because this function will only be called when the page button is clicked function findByPage(curPage,paSize) //When it is called, two parameters need to be passed: the current page number and the page size (how many records are there on a page)
        {
            $.post("ViewRainByPageServlet",{currentPage:curPage,pageSize:paSize},function (data) //Send ajax request {
                var totalCount=data.totalCount;//Total number of recordsvar totalPage=data.totalPage;//Total number of pagesvar currentPage=data.currentPage;//Current page numberif(currentPage==1)//If the current page number is 1 and the user clicks on the previous page, set class="disabled" to display a "disabled" icon{
                    var str = ' <li class="disabled" onclick="findByPage('+(currentPage-1)+',5)">\n' +
                        ' <a href="#" aria-label="Previous">\n' +
                        ' <span aria-hidden="true">&laquo;</span>\n' +
                        ' </a>\n' +
                        ' </li>';

                }
                else //If it is not the first page, the previous page button is in normal style {
                    var str=' <li οnclick="findByPage('+(currentPage-1)+',5)">\n' +
                        ' <a href="#" aria-label="Previous">\n' +
                        ' <span aria-hidden="true">&laquo;</span>\n' +
                        ' </a>\n' +
                        ' </li>';

                }


                //The middle number part of the paging strip for(var i=1;i<=totalPage;i++)
                {
                    if(i==currentPage)//If the current number is equal to the current page number currentPage, set class="active", that is, the page number is highlighted {

                        var item='<li οnclick="findByPage('+i+',5);" class="active"><a href="#">'+i+'</a></li>';
                    }
                    else
                    {
                        var item='<li οnclick="findByPage('+i+',5);"><a href="#">'+i+'</a></li>';
                    }


                    str=str+item;

                }
                if(currentPage==totalPage)//If the current page number is the last page and the user clicks on the next page, set class="disabled" so that a "disabled" icon appears {
                    var strend='<li class="disabled" onclick="findByPage('+(currentPage+1)+',5)">\n' +
                        ' <a href="#" aria-label="Next">\n' +
                        ' <span aria-hidden="true">&raquo;</span>\n' +
                        ' </a>\n' +
                        ' </li>\n' +
                        ' <span style="font-size: 24px" id="total_sp">Total '+totalCount+' records, total '+totalPage+' pages</span>';

                }
                else //If it is not the last page, it is the normal style {
                    var strend='<li οnclick="findByPage('+(currentPage+1)+',5)">\n' +
                        ' <a href="#" aria-label="Next">\n' +
                        ' <span aria-hidden="true">&raquo;</span>\n' +
                        ' </a>\n' +
                        ' </li>\n' +
                        ' <span style="font-size: 24px" id="total_sp">Total '+totalCount+' records, total '+totalPage+' pages</span>';

                }
                str=str+strend;
                $("#fenyelan").html(str);//Change the content of the paging strip//Table string var tableStr='<caption style="text-align: center;font-size: 24px">Rainfall information overview</caption>\n' +
                    ' <tr class="success">\n' +
                    ' <th style="text-align: center">id</th>\n' +
                    ' <th style="text-align: center">Region</th>\n' +
                    ' <th style="text-align: center">Rainfall (mm)</th>\n' +
                    ' <th style="text-align: center">Month</th>\n' +
                    ' <th style="text-align: center">Release Date</th>\n' +
                    ' </tr>';
                var array=data.list;//Object array of specific content for(var i=0;i<array.length;i++)//Traverse the object group {
                    var obj=array[i]; //An element of an array is an object var id=obj.id;
                    var area=obj.area;
                    var precipitation = obj.precipitation;
                    var month=obj.month;
                    var releaseDate=obj.releaseDate;
                    //A row of recorded strings var oneRecord = '<tr class="info">\n' +
                        ' <td style="text-align: center">'+id+'</td>\n' +
                        ' <td style="text-align: center">'+area+'</td>\n' +
                        ' <td style="text-align: center">'+precipitation+'</td>\n' +
                        ' <td style="text-align: center">'+month+'</td>\n' +
                        ' <td style="text-align: center">'+releaseDate+'</td>\n' +
                        ' </tr>';

                    tableStr=tableStr+oneRecord; //Append table string, each time a record is traversed, a row will be added}
                $("#rain_table").html(tableStr);//Change the content in the table});//ajax request end

        }//Page button click function end

    </script>
</head>
<body>
<div class="container">
    <div class="row">

        <table class="table table-bordered table-hover" id="rain_table">
            <caption style="text-align: center;font-size: 24px">Rainfall information at a glance</caption>
            <tr class="success">
                <th style="text-align: center">id</th>
                Region
                <th style="text-align: center">Rainfall (mm)</th>
                <th style="text-align: center">Month</th>
                <th style="text-align: center">Release Date</th>
            </tr>
        </table>


        <nav aria-label="Page navigation">
            <ul class="pagination" id="fenyelan">
                <li>
                    <a href="#" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>
                <li><a href="#">1</a></li>
                <li>
                    <a href="#" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
                <span style="font-size: 24px" id="total_sp">Total 2 records, total 1 page</span>
            </ul>
        </nav>



    </div>

</div>

</body>
</html>

7. Effect display

This is just a simple pagination bar, without the effect of Baidu's pagination bar "first five and last four". When the amount of data becomes very large, this paging bar will take up a lot of space. If you have time, optimize it. As for the Jquery code, it is clearly explained in the code comments, so I will not explain it in detail here.

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Ajax solves cross-domain problem by setting CORS response header to achieve cross-domain case study
  • Three-level linkage provincial and municipal ajax code
  • JSON, AJAX, Maven Basics
  • Ajax login verification implementation code
  • Ajax realizes the linkage between provinces, cities and districts
  • Preliminary implementation of Ajax (using vscode+node.js+express framework)
  • How to use AJAX to obtain Django backend data
  • Detailed explanation of the parsererror error case in JavaScript solution in ajax

<<:  Linux automatic login example explanation

>>:  Docker deployment of Kafka and Spring Kafka implementation

Recommend

Methods and steps for deploying go projects based on Docker images

Dependence on knowledge Go cross-compilation basi...

MySQL 8.0.18 uses clone plugin to rebuild MGR implementation

Assume that a node in the three-node MGR is abnor...

An example of the calculation function calc in CSS in website layout

calc is a function in CSS that is used to calcula...

Linux series of commonly used operation and maintenance commands (summary)

Table of contents 1. System monitoring 2. File Op...

Import backup between mysql database and oracle database

Import the data exported from the Oracle database...

Summary of common problems and application skills in MySQL

Preface In the daily development or maintenance o...

Docker connection mongodb implementation process and code examples

After the container is started Log in to admin fi...

How to design and create adaptive web pages

With the popularization of 3G, more and more peop...

Build a Scala environment under Linux and write a simple Scala program

It is very simple to install Scala environment in...

Web design experience: Make the navigation system thin

<br />When discussing with my friends, I men...