一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - IntelliJ IDEA中ajax開發實現分頁查詢示例

IntelliJ IDEA中ajax開發實現分頁查詢示例

2021-04-16 11:53稻香的超人不會飛 Java教程

這篇文章主要介紹了IntelliJ IDEA中ajax開發實現分頁查詢,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

javaee三層架構實現ajax分頁查詢

開發環境:

  1. 系統 window10
  2. ide:intellij idea2017.3.2
  3. 數據庫:mysql5.5
  4. 數據庫連接工具: navicat
  5. 瀏覽器:chrome 版本號 65.0.3325.181

第一步:代碼實現之前期準備

在idea中開發前期配置的工作,網上的帖子很多,我 在這里就不再贅述.主要說三點

在服務器的配置中,紅色框框的兩項要選擇update classes and resource ,選擇了之后可以實現熱部署.

IntelliJ IDEA中ajax開發實現分頁查詢示例

要在此處填寫項目的名稱.作為項目的根路徑

IntelliJ IDEA中ajax開發實現分頁查詢示例

導入jar包的方式如圖所示,在dependencie中點擊加號,選中自己創建好的lib文件夾

IntelliJ IDEA中ajax開發實現分頁查詢示例

導入相關的jar包: c3p0的jar包、dbutils工具類jar包、fastjson的jar包、mysql驅動jar包

IntelliJ IDEA中ajax開發實現分頁查詢示例

在數據庫test03的product表中寫入如下的數據

IntelliJ IDEA中ajax開發實現分頁查詢示例

在idea中為工程分包,以及導入c3p0連接池的配置

IntelliJ IDEA中ajax開發實現分頁查詢示例

注意,c3p0配置文件,要修改成自己的數據庫名稱,以及數據庫密碼

IntelliJ IDEA中ajax開發實現分頁查詢示例

在domain包中,創建product實體類,根據數據庫中product表的字段,在product類中,書寫對應的屬性.生成get set方法.

IntelliJ IDEA中ajax開發實現分頁查詢示例

創建獲取連接池對象的工具類

IntelliJ IDEA中ajax開發實現分頁查詢示例

第二步:無分頁查詢所有的商品信息

實現思路:

jsp/html----->servlet(web層處理請求與響應的數據) -----------> service(service層處理邏輯)----------->dao(dao層處理數據庫操作)

創建產品頁面,向服務器發送請求(獲取所有產品信息)

前端使用了bootstrap響應式開發,可以讓頁面更加美觀,開發更加便捷

頁面信息的代碼如下:

 
?
1
 
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>商品展示列表</title>
  <!--引入bootstrap相關文件-->
  <link rel="stylesheet" href="/ajax_product/bootstrap/css/bootstrap.css" rel="external nofollow" rel="external nofollow" >
  <script type="text/javascript" src="/ajax_product/bootstrap/js/jquery-1.11.3.js"></script>
  <script type="text/javascript" src="/ajax_product/bootstrap/js/bootstrap.js"></script>
</head>
<script type="text/javascript">
  //頁面加載時,向服務器發送請求,接收全部的商品數據
  $(function () {
    //===================未分頁,展示所有數據===============================
    var url ="/ajax_product/product";
    //=====向服務器發送post請求
    $.post(url,function (data) {
      //解析服務器端傳過來的全部數據
      //============================向表格中展示商品信息
      var products = eval(data);
      //遍歷數據
      for (var i = 0; i < products.length; i++) {
        //遍歷每一行的數據
        var protd =$("<tr><td>"+products[i].id+"</td><td>"+products[i].name+"</td><td>"+products[i].count+"</td><td>"+products[i].price+"</td></tr>");
        // 并添加到表格中,添加數據到表格中
        $("#tab").append(protd);
      }
    },"json")
  })
</script>
 
<body>
<h3 align="center">促銷商品展示</h3>
<div class="container">
  <!--商品的表格占一行-->
  <div class="row">
    <div class="col-md-12">
      <!--table-hover表示當鼠標移入這一行表格的時候,顏色變化
        table-bordered表示給表格加邊框
      -->
      <table class="table table-hover table-bordered" id="tab">
        <tr>
          <th>編號</th>
          <th>商品名稱</th>
          <th>商品數量</th>
          <th>商品單價</th>
        </tr>
      </table>
    </div>
  </div>
</div>
</body>
</html>

創建一個servlet來接收請求,獲取所有的產品信息

在idea中,創建servlet如下圖所示

IntelliJ IDEA中ajax開發實現分頁查詢示例

在這里不勾選自動生成注解

IntelliJ IDEA中ajax開發實現分頁查詢示例

點擊ok之后,idea會自動跳轉到web.xml文件中,自動寫好了servlet的全路徑名,只需寫url-pattern即可

注意url-pattern需要寫得與ajax請求中的servlet一致.

IntelliJ IDEA中ajax開發實現分頁查詢示例

web層servlet的代碼如下:

 
?
1
 
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.thc.web;
 
import com.alibaba.fastjson.jsonobject;
import com.thc.service.productservice;
 
import javax.servlet.servletexception;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import java.io.ioexception;
import java.sql.sqlexception;
import java.util.list;
 
public class product extends httpservlet {
  protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
    //處理響應與請求的亂碼
    request.setcharacterencoding("utf-8");
    response.setcontenttype("text/html;charset=utf-8");
 
    //由于是顯示所有的產品信息,沒有參數接收
    //需要調用服務層查找所有數據的方法,獲取結果,響應給客戶端
    productservice service = new productservice();
 
    try {
      //調用業務層的方法,獲取所有的商品
      list<com.thc.domain.product> allprouct = service.findallprouct();
 
      //把得到的數據,轉為json類型的數據
      string jsonstring = jsonobject.tojsonstring(allprouct);
      //回寫給瀏覽器
      response.getwriter().write(jsonstring);
    } catch (sqlexception e) {
      e.printstacktrace();
    }
 
  }
 
  protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
    dopost(request,response);
  }
}

在service層,從dao層獲取數據,返回給web層的servlet

web層調用service層的代碼如下

 
?
1
 
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.thc.service;
import com.thc.dao.productdao;
import com.thc.domain.product;
import java.sql.sqlexception;
import java.util.list;
 
public class productservice {
  //在service層,從dao層獲取數據,返回數據給web層
  public list<product> findallprouct() throws sqlexception {
    productdao dao = new productdao();
    //調用dao層查詢所有的商品
    list<product> allproduct = dao.findallproduct();
    return allproduct;
 
  }
}

在dao層從服務器中查詢數據,給service層

 
?
1
 
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.thc.dao;
import com.thc.domain.product;
import com.thc.utils.jdbcutils;
import org.apache.commons.dbutils.queryrunner;
import org.apache.commons.dbutils.handlers.beanlisthandler;
import java.sql.sqlexception;
import java.util.list;
//=================dao層專門負責數據庫操作
public class productdao {
  //===========查詢所有商品信息
  public list<product> findallproduct() throws sqlexception {
    //利用dbutils,創建queryrunner核心對象
    queryrunner qr = new queryrunner(jdbcutils.getdatasource());
    //書寫sql語句,查詢所有的商品
    string sql = "select * from product";
    //把商品到的商品,轉為list集合,泛型為product
    list<product> products = qr.query(sql, new beanlisthandler<>(product.class));
    return products;
  }
}

dao層拿到數據后,傳遞給service層,service層再傳遞給web層的servlet,servlet拿到數據后,是保存在list集合中的,再把list集合轉為json數據類型,寫給瀏覽器.前端頁面中的如下代碼,就是在解析servlet返回的json數據

 
?
1
 
2
3
4
5
6
7
8
9
10
11
12
$.post(url,function (data) {
      //解析服務器端傳過來的全部數據
      //============================向表格中展示商品信息
      var products = eval(data);
      //遍歷數據
      for (var i = 0; i < products.length; i++) {
        //遍歷每一行的數據
        var protd =$("<tr><td>"+products[i].id+"</td><td>"+products[i].name+"</td><td>"+products[i].count+"</td><td>"+products[i].price+"</td></tr>");
        // 并添加到表格中,添加數據到表格中
        $("#tab").append(protd);
      }
    },"json")

通過谷歌瀏覽器自帶的抓包工具,可以看到servlet響應的數據

IntelliJ IDEA中ajax開發實現分頁查詢示例

把響應的數據全部復制下來,就是如下的數據.一個數組中嵌套了產品的對象.

對象中都是以鍵值對的形式存在的.

例如第一個數據中,鍵為count,值為100. 鍵為id,值為1,鍵為name,值為電視機,鍵為price 值為2000

 
?
1
 
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
[
  {"count":100,"id":1,"name":"電視機","price":2000},
  {"count":200,"id":2,"name":"洗衣機","price":1000},
  {"count":300,"id":3,"name":"空調","price":3000},
  {"count":50,"id":4,"name":"投影儀","price":2000},
  {"count":1000,"id":5,"name":"hp電腦","price":4000},
  {"count":100,"id":6,"name":"蘋果手機","price":5000},
  {"count":60,"id":7,"name":"縫紉機","price":2000},
  {"count":100,"id":8,"name":"小米盒子","price":2200},
  {"count":300,"id":9,"name":"飲水機","price":2000},
  {"count":200,"id":10,"name":"凈水器","price":2000},
  {"count":500,"id":11,"name":"電暖器","price":2000},
  {"count":100,"id":12,"name":"榨汁機","price":399},
  {"count":200,"id":13,"name":"電壓力鍋","price":498},
  {"count":300,"id":14,"name":"電飯煲","price":299},
  {"count":50,"id":15,"name":"微波爐","price":1299},
  {"count":200,"id":16,"name":"豆漿機","price":199},
  {"count":300,"id":17,"name":"電磁爐","price":398},
  {"count":500,"id":18,"name":"加濕器","price":99},
  {"count":250,"id":19,"name":"剃須刀","price":98},
  {"count":1000,"id":20,"name":"舒膚佳","price":16.5},
  {"count":1200,"id":21,"name":"雕牌","price":8.8},
  {"count":1500,"id":22,"name":"立白","price":9.9}
]

不分頁的情況下,展示的效果如下:

一個頁面中,把所有的數據都展示出來了,如果數據非常多,例如上百度搜索一個關鍵詞,結果可能有上萬上億條,一次性從數據庫中,拿這么多的結果給瀏覽器,是很長的時間的,用戶體驗極差,因此需要分頁技術.采用物理分頁,

一次只從數據庫中查詢當前頁面需要的信息.

IntelliJ IDEA中ajax開發實現分頁查詢示例

第三步:傳遞當前頁面數和每頁顯示的數量給服務器

html頁面中需要增加當前頁面數和每頁顯示的數量這兩個變量,傳遞給服務器

更改代碼的如下圖所示:

IntelliJ IDEA中ajax開發實現分頁查詢示例

在servlet層需要接收參數,并且從service層查詢對應的當前頁的數據,代碼如下:

 
?
1
 
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class product extends httpservlet {
  protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
    //處理響應與請求的亂碼
    request.setcharacterencoding("utf-8");
    response.setcontenttype("text/html;charset=utf-8");
    //當前頁面
    int pageno = integer.parseint(request.getparameter("pageno"));
    //每頁的顯示條數
    int pagesize = integer.parseint(request.getparameter("pagesize"));
    //由于是顯示所有的產品信息,沒有參數接收
    //需要調用服務層查找所有數據的方法,獲取結果,響應給客戶端
    productservice service = new productservice();
    try {   
      //根據當前頁和每頁顯示的數目,來從service層,獲取數據
      list<com.thc.domain.product> product = service.findproduct(pageno, pagesize);
      string jsonstring = jsonobject.tojsonstring(product);
      //回寫給瀏覽器
      response.getwriter().write(jsonstring);
    } catch (sqlexception e) {
      e.printstacktrace();
    }
  }
  protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
    dopost(request,response);
  }
}

service層新增的查找當前頁面數據方法

 
?
1
 
2
3
4
5
public list<product> findproduct(int pageno, int pagesize) throws sqlexception {
    productdao dao = new productdao();
    list<product> product = dao.findproduct(pageno, pagesize);
    return product;
  }

dao層新增的從數據庫查找當前頁面的方法

 
?
1
 
2
3
4
5
6
7
8
9
public list<product> findproduct(int pageno, int pagesize) throws sqlexception {
    queryrunner qr = new queryrunner(jdbcutils.getdatasource());
    string sql ="select * from product limit ?,?";
    //limit第一個參數:從數據庫中的哪里開始查,索引是從0開始的
    //第二個參數:每次查多少個
    //第一個參數的規律是:當前頁數減一,乘以每頁查詢的個數
    list<product> productlist = qr.query(sql, new beanlisthandler<>(product.class), (pageno - 1) * pagesize, pagesize);
    return productlist;
  }

瀏覽器端顯示如下圖所示:每次只會顯示pagesize(當前的值為6)個數的商品信息.

但是還不能動態的通過點擊頁面按鈕來實現翻頁.

IntelliJ IDEA中ajax開發實現分頁查詢示例

那么就要考慮頁面如何顯示分頁條以及數據該如何封裝?

我們知道頁面的分頁條 顯示 的頁數是動態變化的 ,總頁數 =數據的總條數/每頁顯示的數據,要向上取整。也就是說,我們的頁面除了需要list<product>數據之外,還需要數據的總條數、總頁數、當前頁、每頁顯示數量。另外當前頁pageno也是動態變化的,在頁面上點擊多少頁,pageno就是幾。所以, 我們需要再創建一個javabean(pagebean.java)來封裝這些數據 ,在服務端得到這些數據之后轉成json數據發送給客戶端顯示。

第四步:將頁面的相關數據封裝為一個javabean

在domain包內創建一個類,名為pagebean,屬性如下:

 
?
1
 
2
3
4
5
private int pageno;//當前頁數
private int pagesize;//每頁顯示的數量
private int totalcount;//一共有多少個商品信息數據
private int totalpage;//一共有多少頁數據
private list<product> products;//商品信息數據的集合

在web層傳遞service層當前頁面數(pageno),和每頁顯示的條數(pagesize),返回給web層一個pagebean

web層的最終代碼如下

 
?
1
 
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class product extends httpservlet {
  protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
    //處理響應與請求的亂碼
    request.setcharacterencoding("utf-8");
    response.setcontenttype("text/html;charset=utf-8");
    //當前頁面
    int pageno = integer.parseint(request.getparameter("pageno"));
    //每頁的顯示條數
    int pagesize = integer.parseint(request.getparameter("pagesize"));
    //由于是顯示所有的產品信息,沒有參數接收
    //需要調用服務層查找所有數據的方法,獲取結果,響應給客戶端
    productservice service = new productservice();
    try {
      /* 調用業務層的方法,獲取所有的商品
      list<com.thc.domain.product> allprouct = service.findallprouct();
 
      把得到的數據,轉為json類型的數據
      string jsonstring = jsonobject.tojsonstring(allprouct);*/
 
      //根據當前頁和每頁顯示的數目,來從service層,獲取數據
      //list<com.thc.domain.product> product = service.findproduct(pageno, pagesize);
      //===============從web層拿到pagebean的數據=================================
      pagebean pagebean = service.findpageinfo(pageno, pagesize);
      //===============把數據轉為json===============================
      string jsonstring = jsonobject.tojsonstring(pagebean);
      //================回寫給瀏覽器====================
      response.getwriter().write(jsonstring);
    } catch (sqlexception e) {
      e.printstacktrace();
    }
  }
  protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
    dopost(request,response);
  }
}

在service需要獲取pagebean的全部信息,pageno和pagesize是已知的.需要從dao層獲取商品的信息數據,list集合,還需要獲取總的商品信息數據totalcount.總共有多少頁可以通過總數據除以每頁顯示的數據,并向上取整.

service層的最終代碼如下:

 
?
1
 
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class productservice {
  //在service層,從dao層獲取數據,返回數據給web層
 
  //=========service層處理所有商品信息的數據給web層====================
  public list<product> findallprouct() throws sqlexception {
    productdao dao = new productdao();
    //調用dao層查詢所有的商品
    list<product> allproduct = dao.findallproduct();
    return allproduct;
  }
 
  //============service層查詢某個特定頁面的數據給web層=================================
  public list<product> findproduct(int pageno, int pagesize) throws sqlexception {
    productdao dao = new productdao();
    list<product> product = dao.findproduct(pageno, pagesize);
    return product;
  }
 
  //============service層封裝pagebean數據===================================
  public pagebean findpageinfo(int pageno, int pagesize) throws sqlexception {
    productdao dao = new productdao();
    list<product> product = dao.findproduct(pageno, pagesize);
    int totalcount = dao.findtotalcount();
    pagebean pb = new pagebean();
    //封裝數據
    pb.settotalcount(totalcount);
    pb.setpageno(pageno);
    pb.setpagesize(pagesize);
    pb.setproducts(product);
    
   //向上取整,計算總頁數,不要忘了乘以1.0,否則會少一頁數據
    int totalpage = (int) math.ceil(totalcount*1.0/pagesize);
 
    pb.settotalpage(totalpage);
    //把數據給servlet
    return pb;
  }
}

在dao層,新增了一個方法,用于查詢數據庫總信息的總個數

dao層最終的代碼如下

 
?
1
 
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//=================dao層專門負責數據庫操作
public class productdao {
 
  //===========查詢所有商品信息
  public list<product> findallproduct() throws sqlexception {
    //利用dbutils,創建queryrunner核心對象
    queryrunner qr = new queryrunner(jdbcutils.getdatasource());
    //書寫sql語句,查詢所有的商品
    string sql = "select * from product";
    //把商品到的商品,轉為list集合,泛型為product
    list<product> products = qr.query(sql, new beanlisthandler<>(product.class));
    return products;
  }
//=======================查詢當前頁的產品信息=====================
  public list<product> findproduct(int pageno, int pagesize) throws sqlexception {
    queryrunner qr = new queryrunner(jdbcutils.getdatasource());
    string sql ="select * from product limit ?,?";
    //limit第一個參數:從數據庫中的哪里開始查,索引是從0開始的
    //第二個參數:每次查多少個
    //第一個參數的規律是:當前頁數減一,乘以每頁查詢的個數
    list<product> productlist = qr.query(sql, new beanlisthandler<>(product.class), (pageno - 1) * pagesize, pagesize);
    return productlist;
  }
//===============查詢總共有多少條數據=================
  public int findtotalcount() throws sqlexception {
    queryrunner qr = new queryrunner(jdbcutils.getdatasource());
    string sql = "select count(*) from product";
    long countl =(long) qr.query(sql, new scalarhandler());
    return countl.intvalue();
  }
}

第五步:處理前端頁面

在table標簽的下面,增加一行,提供分頁的組件.并把li代碼注釋掉,因為需要動態展示.

IntelliJ IDEA中ajax開發實現分頁查詢示例

先聲明需要接收的參數變量

 
?
1
 
2
3
4
5
var url ="/ajax_product/product";
var pageno=1;//當前頁面設置為1
var pagesize=6;//每頁顯示6條商品信息
var totalpage;//一共有多少頁數據
var products;//商品的數據信息

寫好了ajax的post請求之后,抓包測試瀏覽器是否接收到數據

 
?
1
 
2
3
4
$.post(
  url,//給服務器傳送數據的地址
  {"pageno": pageno, "pagesize": pagesize},//給瀏覽器傳遞當前頁面數和每頁顯示的條數
  function (data) {})

在抓包拿到了如下 的數據

 
?
1
 
2
3
4
5
6
7
8
9
10
{"pageno":1,
 "pagesize":6,
 "products":[{"count":100,"id":1,"name":"電視機","price":2000},
       {"count":200,"id":2,"name":"洗衣機","price":1000},
       {"count":300,"id":3,"name":"空調","price":3000},
       {"count":50,"id":4,"name":"投影儀","price":2000},
       {"count":1000,"id":5,"name":"hp電腦","price":4000},
       {"count":100,"id":6,"name":"蘋果手機","price":5000}],
 "totalcount":22,
 "totalpage":3}

說明服務器端能夠正常給瀏覽器響應數據.再接著寫前端代碼

顯示表格中的數據

先將后端得到的數據解析,再同步到js代碼中,通過pagebean.products獲得所有product對象的數據的數組,再遍歷這個數組,把product屬性的值拼接到表格中去.

代碼如下

 
?
1
 
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$.post(
  url,//給服務器傳送數據的地址
  {"pageno": pageno, "pagesize": pagesize},//給瀏覽器傳遞當前頁面數和每頁顯示的條數
  function (data) {
    //解析服務器端傳過來的全部pagebean數據,格式為json類型
    var pagebean = eval(data);
    //同步數據
    pageno=pagebean.pageno;
    pagesize=pagebean.pagesize;
    totalpage=pagebean.totalpage;
    products=pagebean.products;
    //顯示表格中的數據===============================================
    for (var i = 0; i < products.length; i++) {
      //遍歷每一行的數據
      var protd =$("<tr><td>"+products[i].id+"</td><td>"+products[i].name+"</td>              <td>"+products[i].count+"</td><td>"+products[i].price+"</td>            </tr>");
      // 并添加到表格中,添加數據到表格中
      $("#tab").append(protd);
    }
  },"json")

這段代碼寫完后,可開啟服務器,測試能否獲取數據到表格中.經測試成功顯示數據.

IntelliJ IDEA中ajax開發實現分頁查詢示例

顯示分頁條的數據

先顯示上一頁與下一頁的數據

 
?
1
 
2
3
4
5
6
7
8
9
10
11
//顯示分頁條的數據
//先不考慮功能,先能顯示出來
//顯示上一頁
var preli=$('<li class="disabled"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >上一頁</a></li>');
//通過類選擇器,添加進去
$(".pager").append(preli);
 
//顯示下一頁
var nextli=$('<li class="disabled"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >下一頁</a></li>');
//通過類選擇器,添加進去
$(".pager").append(nextli);

進測試效果如下:

IntelliJ IDEA中ajax開發實現分頁查詢示例

顯示頁碼數據:

 
?
1
 
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//顯示分頁條的數據
//先不考慮功能,先能顯示出來
//顯示上一頁
var preli=$('<li class="disabled"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >上一頁</a></li>');
//通過類選擇器,添加進去
$(".pager").append(preli);
 
//遍歷顯示頁碼
for (var i = 1; i <= totalpage; i++) {
  //創建li標簽
  var li=$('<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >'+i+'</a></li>');
  //通過類選擇器,添加到ul中
  $(".pager").append(li);
}
 
//顯示下一頁
var nextli=$('<li class="disabled"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >下一頁</a></li>');
//通過類選擇器,添加進去
$(".pager").append(nextli);

效果如下圖所示:

IntelliJ IDEA中ajax開發實現分頁查詢示例

當前頁高亮顯示

由于bootstrap中,pager類不支持高亮顯示,因此把分頁的類換為pagination.

高亮的邏輯是,在遍歷的是否,判斷是否為當前頁(pageno).

給li標簽添加class的active 屬性

 
?
1
 
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//遍歷顯示頁碼
for (var i = 1; i <= totalpage; i++) {
  var li;
  if(i===pageno){
    //=========是當前頁,就高亮顯示
    li=$('<li class="active"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >'+i+'</a></li>');
    //通過類選擇器,添加到ul中
    $(".pagination").append(li);
  }else{
    //========不是當前頁,不高亮顯示
    li=$('<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >'+i+'</a></li>');
    //通過類選擇器,添加到ul中
    $(".pagination").append(li);
  }
}

效果如下

IntelliJ IDEA中ajax開發實現分頁查詢示例

給頁碼添加點擊事件,切換數據.

當前頁不需要添加點擊事件

IntelliJ IDEA中ajax開發實現分頁查詢示例

給頁數里面的a標簽添加onclick事件,綁定一個skippage()函數,skippage()函數里面所做的操作實際上就是我們獲取第1頁數據的向服務器發送ajax的post請求的操作,所以 把$(function(){})的代碼復制到skippage()函數中 ,然后在頁面加載完成時調用skippage()函數,傳入1就表示默認加載第1頁數據。此時,$(function(){})只會執行一次.而skippage()成了遞歸函數,自己調用自己.但一次點擊事件,只會調用一次skippage方法,與java中的遞歸不太一樣.

IntelliJ IDEA中ajax開發實現分頁查詢示例

執行完此段代碼后,點擊不同的代碼,發現表格的內容以及分頁條會不斷疊加

如下圖所示:

IntelliJ IDEA中ajax開發實現分頁查詢示例

每次加載數據時,清空數據. 清空分頁條

IntelliJ IDEA中ajax開發實現分頁查詢示例

添加了清空分頁條的代碼后,發現,分頁條沒有疊加了,但是表格還在疊加

IntelliJ IDEA中ajax開發實現分頁查詢示例

清空表格

$("#tab").empty(); 給表格執行清空代碼后發現如下現象:

IntelliJ IDEA中ajax開發實現分頁查詢示例

表格的第一行標題沒有了,所以需要用選擇器,把第一行排除在外.

IntelliJ IDEA中ajax開發實現分頁查詢示例

$("#tab tr:not(:first)")的含義是

先根據id選擇器,選擇表格

再由層級選擇器,選擇tr行

再由基本選擇器not中嵌套基本選擇器first,代表不是第一行

整體的意思是,選擇了表格了不是第一行的元素,調用empty()方法,刪除匹配的元素集合中所有的子節點。

測試后,能夠不刪除第一行數據

IntelliJ IDEA中ajax開發實現分頁查詢示例

上一頁判斷是否可用,以及切換頁碼功能

如果當前頁是第一頁,上一頁功能就不可用.

如果當前頁不是第一頁,就添加點擊事件,切換到上一頁,把頁碼減一.

 
?
1
 
2
3
4
5
6
7
8
9
10
//顯示上一頁,判斷是否可用
var preli;
if(pageno===1){
  //如果當前頁是第一頁,上一頁功能就不可用
  preli=$('<li class="disabled"><a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >上一頁</a></li>');
}else{
  preli=$('<li><a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="skippage('+(pageno-1)+')">上一頁</a></li>');
}
//通過類選擇器,添加進去
$(".pagination").append(preli);

下一頁判斷是否可用,以及切換頁碼功能

如果當前頁是最后一頁,上一頁功能就不可用.

 如果當前頁不是最后一頁,就添加點擊事件,切換到下一頁,把頁碼加一.

 
?
1
 
2
3
4
5
6
7
8
9
10
11
//顯示下一頁,判斷是否可用
var nextli;
if(pageno===totalpage){
  //如果當前頁是最后一頁,上一頁功能就不可用.
  nextli=$('<li class="disabled"><a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >下一頁</a></li>');
}else {
  //如果當前頁不是最后一頁,就添加點擊事件,切換到上一頁,把頁碼減一.
  nextli=$('<li><a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="skippage('+(pageno+1)+')">下一頁</a></li>');
}
//通過類選擇器,添加進去
$(".pagination").append(nextli);

至此,前端頁面的代碼全部完成,功能全部實現

前端頁面的全部代碼如下

 
?
1
 
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>商品展示列表</title>
  <!--引入bootstrap相關文件-->
  <link rel="stylesheet" href="/ajax_product/bootstrap/css/bootstrap.css" rel="external nofollow" rel="external nofollow" >
  <script type="text/javascript" src="/ajax_product/bootstrap/js/jquery-1.11.3.js"></script>
  <script type="text/javascript" src="/ajax_product/bootstrap/js/bootstrap.js"></script>
</head>
<script type="text/javascript">
  var url ="/ajax_product/product";
  var pageno=1;//當前頁面設置為1
  var pagesize=5;//每頁顯示6條商品信息
  var totalpage;//一共有多少頁數據
  var products;//商品的數據信息
 
  //頁面加載時,向服務器發送請求,接收全部的商品數據
  $(function () {
    skippage(1);
  });
 
  function skippage(page) {
    //===========分頁時的post請求===================================
    pageno=page;
    //=====向服務器發送post請求
    $.post(
      url,//給服務器傳送數據的地址
      {"pageno": pageno, "pagesize": pagesize},//給瀏覽器傳遞當前頁面數和每頁顯示的條數
      function (data) {
        //解析服務器端傳過來的全部pagebean數據,格式為json類型
        var pagebean = eval(data);
        //同步數據
        pageno=pagebean.pageno;
        pagesize=pagebean.pagesize;
        totalpage=pagebean.totalpage;
        products=pagebean.products;
 
        //顯示表格中的數據===============================================
        //$("#tab").empty();
        $("#tab tr:not(:first)").empty();
 
        for (var i = 0; i < products.length; i++) {
          //遍歷每一行的數據
          var protd =$("<tr><td>"+products[i].id+"</td><td>"+products[i].name+"          </td><td>"+products[i].count+"</td><td>"+products[i].price+"</td></tr>");
          // 并添加到表格中,添加數據到表格中
          $("#tab").append(protd);
        }
 
        //顯示分頁條的數據========================================================
 
        //清空分頁條
        $(".pagination").empty();
 
        //先不考慮功能,先能顯示出來
        //顯示上一頁,判斷是否可用
        var preli;
        if(pageno===1){
          //如果當前頁是第一頁,上一頁功能就不可用.
          preli=$('<li class="disabled"><a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >上一頁</a>             </li>');
        }else{
          //如果當前頁不是第一頁,就添加點擊事件,切換到上一頁,把頁碼減一.
          preli=$('<li><a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="skippage('+(pageno-           1)+')">上一頁</a></li>');
        }
        //通過類選擇器,添加進去
        $(".pagination").append(preli);
 
        //遍歷顯示頁碼
        for (var i = 1; i <= totalpage; i++) {
          var li;
          if(i===pageno){
            //=========是當前頁,就高亮顯示
            li=$('<li class="active"><a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >'+i+'</a>               </li>');
            //通過類選擇器,添加到ul中
            $(".pagination").append(li);
          }else{
            //========不是當前頁,不高亮顯示.添加點擊事件,參數傳遞為當前頁碼
            li=$('<li><a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow"                          onclick="skippage('+i+')">'+i+'</a></li>');
            //通過類選擇器,添加到ul中
            $(".pagination").append(li);
          }
        }
        //顯示下一頁,判斷是否可用
        var nextli;
        if(pageno===totalpage){
           //如果當前頁是最后一頁,上一頁功能就不可用.
          nextli=$('<li class="disabled"><a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >下一頁</a>         </li>');
        }else {
          //如果當前頁不是最后一頁,就添加點擊事件,切換到上一頁,把頁碼減一.
          nextli=$('<li><a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="skippage('+           (pageno+1)+')">下一頁</a></li>');
        }
        //通過類選擇器,添加進去
        $(".pagination").append(nextli);
 
      },"json")
  }
</script>
 
<body>
<h3 align="center">促銷商品展示</h3>
<div class="container">
  <!--商品的表格占一行-->
  <div class="row">
    <div class="col-md-12">
      <!--table-hover表示當鼠標移入這一行表格的時候,顏色變化
        table-bordered表示給表格加邊框
      -->
      <table class="table table-hover table-bordered" id="tab">
        <tr>
          <th>編號</th>
          <th>商品名稱</th>
          <th>商品數量</th>
          <th>商品單價</th>
        </tr>
      </table>
    </div>
  </div>
 
  <div class="row">
    <div class="col-md-4 col-md-offset-4" >
      <nav>
        <ul class="pagination">
         <!--此處代碼由js動態生成
          -->
        </ul>
      </nav>
    </div>
  </div>
 
</div>
</body>
</html>

總結

此分頁功能,用到了javaee的三層架構的思想.每一層各司其職,做各自的負責的事情.前端部分為難點.需要處理的細節很多.前端涉及到了ajax和jquery.jquery的一些語法與選擇器的相關的東西要非常熟練.還用到了bootrap響應式開發,讓前端頁面的布局更加方便.

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

原文鏈接:https://www.jianshu.com/p/1fd6b39e98ac

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 午夜片神马影院福利 | aaa级黄色片 | 午夜福利体验免费体验区 | 微拍秒拍99福利精品小视频 | 边摸边吃奶又黄激烈视频韩国 | 西西人体大胆啪啪私拍色约约 | 奇米白色 | 99久久99久久免费精品蜜桃 | 奇米777四色精品综合影院 | 久久aa毛片免费播放嗯啊 | 色热综合| 四虎永久网址影院 | 国内精品91东航翘臀女神在线 | 国产精品一区三区 | 欧美春宫| 亚洲精品无码不卡在线观看 | 雪恋电影完整版免费观看 | 日本中文字幕在线精品 | 亚洲精品国产一区二区三区在 | 精品国产成人高清在线 | japan在线观看| 亚洲国产第一区二区香蕉日日 | 日本五十路六十30人8时间 | 国产免费一区二区三区免费视频 | 男男按摩1069gⅴ | 欧美美女一区二区三区 | 国产成人免费视频 | 亚洲黄色网页 | 国产日韩一区二区 | 精品久久久久久 | 国产高清视频免费最新在线 | 人人揉人人爽五月天视频 | 1024人成网站色 | 俺来操 | 天天舔天天射 | 色综合欧美色综合七久久 | 国产精品馆 | 娇妻与老头绿文小说系列 | 精品久久成人免费第三区 | 免费在线视频成人 | 男人女人叉叉叉 |