Home Web Front-end JS Tutorial Use JQuery to write a simple asynchronous paging plug-in_jquery

Use JQuery to write a simple asynchronous paging plug-in_jquery

May 16, 2016 pm 03:11 PM

I wrote a Jquery asynchronous paging plug-in and shared it with me. Please let me know if there are any imperfections.
Take user paging as an example. Let’s take a look at the effect first. The first page is:

Next page or after clicking on the second page:

After clicking on the last page:

Is the effect okay? Let’s see how to use it. First, there must be a Page model in the background:
Page.java:

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

public class Page {

   

 /**

  * 当前页号

  */

 private int currPageNum = 1;

   

   

 /**

  * 总记录数

  */

 private int totalRowSize = 0;

   

 /**

  * 每页记录数

  */

 private int pageRowSize = 10;

   

 public int getCurrPageNum() {

  return currPageNum;

 }

  

 public void setCurrPageNum(int currPageNum) {

  this.currPageNum = currPageNum;

 }

  

 public int getTotalPageNum() {

  int total = (totalRowSize%pageRowSize==0)?(totalRowSize/pageRowSize):(totalRowSize/pageRowSize+1);

  return total;

 }

  

 public int getTotalRowSize() {

  return totalRowSize;

 }

  

 public void setTotalRowSize(int totalRowSize) {

  this.totalRowSize = totalRowSize;

 }

  

 public int getPageRowSize() {

  return pageRowSize;

 }

  

 public void setPageRowSize(int pageRowSize) {

  this.pageRowSize = pageRowSize;

 }

  

 public int getFirstResult(){

  if(getCurrPageNum()<=0) return 0;

    

  return getPageRowSize() * (getCurrPageNum() - 1);

 }

  

 public int getMaxResult() {

  return this.getFirstResult()+this.getPageRowSize();

 }

   

}

Copy after login

Then look at list_user.jsp:

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

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

 <head>

 <title>异步分页</title>

 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

 <link href="../css/local.css" rel="stylesheet" type="text/css" />

 <script type="text/javascript" src="../js/jquery-1.4.2.min.js"></script>

 <script type="text/javascript" src="../js/asyn_page.js"></script>

 <script type="text/javascript">

 var totalRowSize = ${totalRowSize};

 $(document).ready(function(){

  $("#pageWidget").asynPage("/user/findUser_asyn.action","#tbody",buildHtml,totalRowSize);

 });

   

 //构建内容

 function buildHtml(users){

  $.each(users,function(i,user){

   var tr = [

    '<tr>',

     '<td>',user.userId,'</td>',

     '<td>',user.username,'</td>',

     '<td>',user.sex,'</td>',

     '<td>',user.age,'</td>',

     '<td>',user.email,'</td>',

     '<td>',user.address,'</td>',

     '<td>',user.registerTime,'</td>',

     '<td></td>',

    '</tr>'

   ].join('');

   $("#tbody").append(tr);

  });

 }

 </script>

 </head>

 <body>

 <table>

  <thead>

  <tr>

   <th>ID</th>

   <th>用户名</th>

   <th>性别</th>

   <th>年龄</th>

   <th>Email</th>

   <th>地址</th>

   <th>注册时间</th>

   <th>操作</th>

  </tr>

  </thead>

  <tbody id="tbody"></tbody>

 </table>

 <div id="pageWidget" class="page"></div>

 </body>

</html>

Copy after login

You can see that the element with the id of tbody is used as a paging content display container, and the element with the id of pageWidget is used as a paging control display container.
Then a buildHtml() function is provided to specifically build the paging content.
Using the asynchronous paging plug-in is very simple, just call it like this:

1

$("#pageWidget").asynPage("/user/findUser_asyn.action","#tbody",buildHtml,totalRowSize);

Copy after login

This is the simplest call. You can also pass additional query parameters and customize the number of records displayed on each page. For specific usage, see the detailed introduction of the plug-in.
The following is the content of the asynPage plug-in:

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

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

/*

 * ===================AJAX异步分页=================

 *

 * Copyright 2012 8 23, zhutx

 *

 * 假设id为pageWidget的div是你放置分页控件的容器,则按如下形式调用:

 * $("#pageWidget").asynPage("/user/findUser_asyn.action","#tbody",buildHtml,totalRowSize,{"pageRowSize":10});

 * 参数说明:

 * ------------Required-----------

 * 参数一:请求URL

 * 参数二:渲染结果集的页面容器

 * 参数三:负责渲染结果集到页面的函数

 * 参数四:总记录数

 * ------------Optional-----------

 * 参数五(json对象):

 * 属性pageRowSize:每页记录数(不配置,则默认为20)

 * 属性param:请求参数(json格式)

 */

(function($){

 var settings;

 var page;

 var paramStr;

   

 $.fn.asynPage = function(url,contentContainer,buildHtml_fun,totalRowSize,callerSettings){

   

  settings = $.extend({

   currPageNum:1,

   pageRowSize:20,

   param:null

  },callerSettings||{});

   

  settings.contentContainer = $(contentContainer);

  settings.url = url;

  settings.pageWidget = this;

  settings.totalRowSize = totalRowSize;

  settings.buildHtml_fun = buildHtml_fun;

    

  page = new Page(settings.currPageNum,settings.totalRowSize,settings.pageRowSize);

    

  paramStr = makeParamStr(settings.param);

    

  //开始获取数据

  fetchData(page.getCurrPageNum());

    

  return this;

 };

   

 /* 将json转换为请求参数字符串 */

 var trunParamConfig2RequestParamStr = function(json){

  var str = "";

  for(key in json){

   if(str==""){

    str += key+"="+json[key];

   }else{

    str += "&"+key+"="+json[key];

   }

  }

  return str;

 };

   

 /* 将配置参数拼接为请求字符串 */

 var makeParamStr = function(param_json){

  if(param_json==null){

   return "";

  }else{

   return trunParamConfig2RequestParamStr(param_json);

  }

 };

   

 /*

  * 负责获取后台数据,获取完毕后会触发构建分页控件

  */

 var fetchData = function(currPageNum){

    

  page.setCurrPageNum(currPageNum);

  var firstResult = page.getFirstResult();

  var maxResult = page.getMaxResult();

  var pageRowSize = page.getPageRowSize();

    

  var data = null;

  if(paramStr){

   data = paramStr + "&page.currPageNum="+currPageNum+"&page.pageRowSize="+pageRowSize+"&page.firstResult="+firstResult+"&page.maxResult="+maxResult;

  }else{

   data = "page.currPageNum="+currPageNum+"&page.pageRowSize="+pageRowSize+"&page.firstResult="+firstResult+"&page.maxResult="+maxResult;

  }

    

  $.ajax({

   type :"POST",

   url : settings.url,

   data :data,

   success :function(datas){

    settings.contentContainer.empty();

    settings.buildHtml_fun(datas);

    buildPageWidget(page);//触发构建分页控件

   },

   error:function(xmlHttpRequest,textStatus,errorThrown){

    if(textStatus == "error"){

     var error = eval('('+xmlHttpRequest.responseText+')');

     alert("Sorry:"+error.errorCode+","+error.message+"!");

    }

   }

  });

 };

   

 var trunTargetPage = function(pageNum){

  fetchData(pageNum);

 }

   

 /* 为分页控件绑定事件 */

 var bindEvent = function(){

  var links = settings.pageWidget.find("a");

  $.each(links,function(i,link){

   var link = $(link);

   var pageNum = link.attr("pageNum");

   link.click(function(){

    trunTargetPage(pageNum);

   });

  });

 }

   

 /* 构建分页控件的具体算法实现 */

 var buildPageWidget = function(page){

    

  //构建分页控件前,先清理现有控件

  settings.pageWidget.empty();

    

  /* --------------- 下面开始进入真正的分页控件构建过程 -------------- */

    

  /* --------------- 1.开始:构建描述信息(如“共?页,?条记录”) ----------------- */

  settings.pageWidget.append("<div class='total'>共<span>"+page.getTotalPageNum()+"</span>页 <span>"+page.getTotalRowSize()+"</span>条记录</div>");

  settings.pageWidget.append("<ul>");

  /* --------------- 1.结束:构建描述信息(如“共?页,?条记录”) ----------------- */

    

  /* --------------- 2.开始:构建“首页”和“上一页”控件 ------------- */

  var currPageNum = Number(page.getCurrPageNum());

  var totalPageNum = Number(page.getTotalPageNum());

    

  if(currPageNum==1){

   //如果你希望当前页是第一页的时候,也允许“首页”和“上一页”控件出现,则可以在这里进行补充

  }else{

   settings.pageWidget.find("ul").append("<li><a id='' pageNum='1' href='javascript:void(0);' title='首页' class='first'>首页</a></li>");

   settings.pageWidget.find("ul").append("<li><a id='' pageNum='"+(currPageNum-1)+"' href='javascript:void(0);' title='上一页' class='prev'>上一页</a></li>");

  }

  /* --------------- 2.结束:构建“首页”和“上一页”控件 ------------- */

    

  /* --------------- 3.开始:构建分页数字控件 -------------- */

  if(totalPageNum<10){

   for(var i=1;i<=totalPageNum;i++){

    if(i==currPageNum){

     settings.pageWidget.find("ul").append("<li><a id='' pageNum='"+i+"' href='javascript:void(0);' title='' class='current'>"+i+"</a></li>");

    }else{

     settings.pageWidget.find("ul").append("<li><a id='' pageNum='"+i+"' href='javascript:void(0);' title='' class='javascript:trunTargetPage("+i+");'>"+i+"</a></li>");

    }

   }

  //如果总页数>=10

  }else{

   //如果当前页小于5,则显示1-9项,且记忆当前项

   if(currPageNum<5){

    for(var i =1;i<10;i++){

     if(i==currPageNum){

      settings.pageWidget.find("ul").append("<li><a id='' pageNum='"+i+"' href='javascript:void(0);' title='' class='current'>"+i+"</a></li>");

     }else{

      settings.pageWidget.find("ul").append("<li><a id='' pageNum='"+i+"' href='javascript:void(0);' title='' class=''>"+i+"</a></li>");

     }

    }

   //如果当前页>=5,且总页数与当前页的差<4

   }else if(totalPageNum-currPageNum<4){

    for(var i=totalPageNum-8;i<=totalPageNum;i++){

     if(i==currPageNum){

      settings.pageWidget.find("ul").append("<li><a id='' pageNum='"+i+"' href='javascript:void(0);' title='' class='current'>"+i+"</a></li>");

     }else{

      settings.pageWidget.find("ul").append("<li><a id='' pageNum='"+i+"' href='javascript:void(0);' title='' class=''>"+i+"</a></li>");

     }

    }

   //如果当前页>=5,则显示围绕当前页的9项,且记忆当前项 

   }else{

    for(var i=currPageNum-4;i<currPageNum+5;i++){

     if(i==currPageNum){

      settings.pageWidget.find("ul").append("<li><a id='' pageNum='"+i+"' href='javascript:void(0);' title='' class='current'>"+i+"</a></li>");

     }else{

      settings.pageWidget.find("ul").append("<li><a id='' pageNum='"+i+"' href='javascript:void("+i+");' title='' class=''>"+i+"</a></li>");

     }

    }

   }

  }

  /* --------------- 3.结束:构建分页数字控件 -------------- */

    

  /* --------------- 4.开始:构建“下一页”和“尾页”控件 ------------- */

  if(totalPageNum==currPageNum){

   //如果你希望当前页是最后一页的时候,也允许“尾页”和“下一页”控件出现,则可以在这里进行补充

  }else{

   settings.pageWidget.find("ul").append("<li><a id='' pageNum='"+(currPageNum+1)+"' href='javascript:void(0);' title='下一页' class='next'>下一页</a></li>");

   settings.pageWidget.find("ul").append("<li><a id='' pageNum='"+totalPageNum+"' href='javascript:void(0);' title='尾页' class='last'>尾页</a></li>");

  }

  /* --------------- 4.结束:构建“下一页”和“尾页”控件 ------------- */

    

  //还要为控件绑定点击事件

  bindEvent();

 }

   

})(jQuery);

  

/*

 * Page类

 */

function Page(currPageNum,totalRowSize,pageRowSize){

 this.currPageNum = currPageNum;

 this.totalRowSize = totalRowSize;

 this.pageRowSize = pageRowSize;

}

Page.prototype.getCurrPageNum = function(){

 return this.currPageNum;

};

Page.prototype.setCurrPageNum = function(currPageNum){

 this.currPageNum = currPageNum;

};

Page.prototype.getTotalPageNum = function(){

 return (this.totalRowSize%this.pageRowSize==0)&#63;(this.totalRowSize/this.pageRowSize):(Math.floor(this.totalRowSize/this.pageRowSize)+1);

};

Page.prototype.getTotalRowSize = function(){

 return this.totalRowSize;

};

Page.prototype.setTotalRowSize = function(totalRowSize){

 this.totalRowSize = totalRowSize;

};

Page.prototype.getPageRowSize = function(){

 return this.pageRowSize;

};

Page.prototype.setPageRowSize = function(pageRowSize){

 this.pageRowSize = pageRowSize;

};

Page.prototype.getFirstResult = function(){

 if(this.getCurrPageNum()<=0) return 0;

 return this.getPageRowSize() * (this.getCurrPageNum() - 1);

};

Page.prototype.getMaxResult = function(){

 return this.getFirstResult() + this.getPageRowSize();

};

Copy after login

The above is the entire content of this article, I hope it will be helpful to everyone’s study.

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)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles