纯jQuery实现前端分页功能
程序员文章站
2023-09-28 12:50:43
由于之前自己做过jquery分页,就是调用jni接口时,只能用前台分页解决显示问题。最近看到有人提这样的问题:一个请求传过来上万个数据怎么办?于是萌生了写这篇博客的想法。...
由于之前自己做过jquery分页,就是调用jni接口时,只能用前台分页解决显示问题。最近看到有人提这样的问题:一个请求传过来上万个数据怎么办?于是萌生了写这篇博客的想法。
效果展示:
因为核心代码主要在前端jquery,为了简便,后台就用servlet遍历本地磁盘目录文件的形式模拟响应的数据。
本项目的目录结构:
本项目的本地遍历文件夹结构:
处理显示请求的servlet:
package com.cn.action; import com.alibaba.fastjson.json; import com.cn.entity.downloadfile; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import java.io.*; import java.util.arraylist; import java.util.list; import java.util.properties; /** * created by nolimitors on 2017/3/17. */ public class pagesservlet extends httpservlet{ protected void doget(httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception { /** *@author: nolimitor *@params: * @param req * @param resp *@date: 17:55 2017/3/17 */ dopost(req,resp); } protected void dopost(httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception { /** *@author: nolimitor *@params: * @param req * @param resp *@date: 17:55 2017/3/17 */ properties props = new properties(); inputstream in = new bufferedinputstream(new fileinputstream(this.getclass().getresource("/fileroot.properties").getpath())); props.load(in); string rootpath = props.getproperty("root"); list filelist = new arraylist(); file file = new file(rootpath); file []files = file.listfiles(); downloadfile df = new downloadfile(); for(file f:files) { df.setname(f.getname()); df.setfilesize(long.tostring(f.length())); system.out.println(f.getname()); filelist.add(json.tojsonstring(df)); } resp.addheader("content-type","application/json"); resp.setheader("content-type", "text/html;charset=utf-8"); resp.getwriter().print(json.tojsonstring(filelist)); } } pagesservlet
处理下载文件请求的servlet:
package com.cn.action; import javax.servlet.servletexception; import javax.servlet.servletoutputstream; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import java.io.*; import java.net.urlencoder; import java.util.properties; /** * created by nolimitors on 2017/3/20. */ public class downloadfile extends httpservlet { @override protected void dopost(httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception { doget(req,resp); } @override protected void doget(httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception { //获取所要下载文件的路径 properties props = new properties(); inputstream in = new bufferedinputstream(new fileinputstream(this.getclass().getresource("/fileroot.properties").getpath())); props.load(in); string rootpath = props.getproperty("root"); string name = req.getparameter("filename"); name = new string(name.getbytes("iso8859-1"),"utf-8"); system.out.println(name); //处理请求 //读取要下载的文件 file f = new file(rootpath+"\\"+ name); if(f.exists()){ fileinputstream fis = new fileinputstream(f); string filename=java.net.urlencoder.encode(f.getname(),"utf-8"); //解决中文文件名下载乱码的问题 byte[] b = new byte[fis.available()]; fis.read(b); //解决中文文件名下载后乱码的问题 resp.setcontenttype("application/x-msdownload"); resp.setheader("content-disposition", "attachment;filename="+ new string(filename.getbytes("utf-8"),"iso-8859-1")); //获取响应报文输出流对象 servletoutputstream out =resp.getoutputstream(); //输出 out.write(b); out.flush(); out.close(); } } } downloadfile
web.xml配置:
<?xml version="1.0" encoding="utf-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>pageservlet</servlet-name> <servlet-class>com.cn.action.pagesservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>pageservlet</servlet-name> <url-pattern>/dopages</url-pattern> </servlet-mapping> <servlet> <servlet-name>downservlet</servlet-name> <servlet-class>com.cn.action.downloadfile</servlet-class> </servlet> <servlet-mapping> <servlet-name>downservlet</servlet-name> <url-pattern>/download</url-pattern> </servlet-mapping> </web-app> web.xml
前台完整html代码:
<html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <link href="/resource/juqery/css/base/jquery-ui-1.9.2.custom.css" rel="external nofollow" rel="stylesheet"> <link href="/resource/css/css.css" rel="external nofollow" rel="stylesheet"> <script type="application/javascript" src="/resource/common.js"></script> <script type="application/javascript" src="/resource/juqery/js/jquery-1.8.3.js"></script> <script type="application/javascript" src="/resource/juqery/js/jquery-ui-1.9.2.custom.js"></script> </head> <script type="application/javascript"> //请求一次数据,然后存储到js变量中,保证只发送一条请求 var datas; jquery(function() { $.ajax({ type: "post", url: "/dopages", data: "{}", datatype: 'json', success: function(data) { datas = data; getpages(1,5); } }); }); //用于页码跳转方法 function jumpage(totalpage,psize){ var cpage=jquery("#page_no").val(); if(0< cpage && cpage <= totalpage){ getpages(cpage,psize); } else{ alert("out of range"); } } function getpages(pno,psize) { var num;//分页总行数 var totalpage = 0;//分页总页数 var pagesize = psize;//分页每行显示数 var currentpage = pno;//当前页 num = parseint(datas.length);//获取数据行数 if (num / pagesize > parseint(num / pagesize)) { totalpage = parseint(num / pagesize) + 1; } else { totalpage = parseint(num / pagesize); } var startrow = (currentpage - 1) * pagesize + 1;//开始显示的行 var endrow = currentpage * pagesize;//结束显示的行 endrow = (endrow > num) ? num : endrow; var tbody = jquery("#list_data>tbody"); tbody.empty(); jquery.each(datas, function (i, n) { var file = json.parse(n); if (startrow <= parseint(i + 1) && parseint(i + 1) <= endrow) { var row = createrow().appendto(tbody); //多选用,目前暂时未考虑 /* createcolumn().html("<input type='checkbox' id="+"fileid"+(i+1)+" name='fileid'/>").appendto(row);*/ createcolumn().text(i + 1).appendto(row); createcolumn().text(file.name).appendto(row); createcolumn().text(getsize(file.filesize)).appendto(row); var operationcolumn = createcolumn().appendto(row); } //每次执行分页代码时需要将前一次分页的判断结果清空 jquery("#last_page").removeattr("onclick"); jquery("#next_page").removeattr("onclick"); //当前页非第一页时 if (currentpage > 1) { jquery("#last_page").attr("onclick", "getpages(" + (parseint(currentpage) - 1) + "," + psize + ")"); } //当前页小于总页数时 if (currentpage < totalpage) { jquery("#next_page").attr("onclick", "getpages(" + (parseint(currentpage) + 1) + "," + psize + ")"); } //显示当前页码、总页数及生成跳转点击事件 jquery("#end_page").attr("onclick", "getpages(" + (totalpage) + "," + psize + ")"); jquery("#first_page").attr("onclick", "getpages(" + (1) + "," + psize + ")"); jquery("#jump_page").attr("onclick", "jumpage(" + (totalpage) + "," + psize + ")"); jquery("#total_page").val("/" + totalpage + " 页"); jquery("#page_no").val(currentpage); var btndownload = jquery("<button class='btn_download'>下载</button>"); var btndelete = jquery("<button class='btn_delete'>删除</button>"); //批量删除获取文件信息用,目前暂时不用 /*jquery("#"+"fileid"+(i+1)).attr("recordquery",json.stringify(recordquery));*/ btndownload.click(function () { location.href = "/download?filename=" + file.name; }); btndelete.click(function () { recordquery = jquery(this).attr("data-record-query"); var dialogdiv = jquery("<div></div>"); dialogdiv.dialog({ autoopen: false, modal: true, width: 500, position: {my: "center", at: "center", of: jquery(".content_wrapper_hidden")}, title: "文件删除", buttons: [ { text: "确认", click: function () { jquery.post("/delete", file.name, function (data) { location.reload(); }); jquery(this).dialog("close"); } }, { text: "取消", click: function () { jquery(this).dialog("close"); } } ] }); var text = "确认删除 "+ file.name + "?"; dialogdiv.text(text).dialog("open"); }); btndownload.appendto(operationcolumn); btndelete.appendto(operationcolumn); }); jquery(".btn_download,.btn_delete").button(); } function getsize(length) { var len, unit; if (length == 0) { len = 0; unit = "b"; } else if (length < 1024) { len = length; unit = "b"; } else if (length < (1024 * 1024)) { len = (length / 1024); unit = "kb"; } else { len = (length / 1024 / 1024); unit = "mb"; } return new number(len).tofixed(2) + unit; } </script> <style> .data tbody tr td:first-child{ font-weight:bold; cursor: pointer; } </style> <body> <div class="main_wrapper"> <div class="content_wrapper_hidden"> <div class="ui_wrapper"> <table id="list_data" class="data" border="0" cellspacing="0" cellpadding="0" style="width: 100%"> <thead> <tr> <th >num</th> <th >files</th> <th >size</th> <th >operation</th> </tr> </thead> <tbody> </tbody> </table> <!-- 分页用按钮--> <table class="ui-corner-all grey" style="width: 100%"> <tbody align="center" valign="middle"> <tr><td><div id="pagination"> <!-- 全选和批量删除按钮,目前暂时未考虑--> <!--<input type="button" id='fileids' style="background: -moz-linear-gradient(top,#ffffff,#e6e6e6);border-color:#c5c5c5" value="全选"/><input type="button" id='delete_fileids' style="background: -moz-linear-gradient(top,#ffffff,#e6e6e6);border-color:#c5c5c5" value="删除"/>--> <input type="button" id='first_page' style="background: -moz-linear-gradient(top,#ffffff,#e6e6e6);border-color:#c5c5c5" value="首页"/><input type="button" style="background: -moz-linear-gradient(top,#ffffff,#e6e6e6);border-color:#c5c5c5" id='last_page' value="上一页"/><input type="button" id='next_page' style="background: -moz-linear-gradient(top,#ffffff,#e6e6e6);border-color:#c5c5c5" value="下一页"/><input type="button" style="background: -moz-linear-gradient(top,#ffffff,#e6e6e6);border-color:#c5c5c5" id='end_page' value="尾页"/><input type="button" style="background: -moz-linear-gradient(top,#ffffff,#e6e6e6);border-color:#c5c5c5" id='jump_page' value="跳转"/> <input autocomplete="off" class="ui-autocomplete-input" id="page_no" style="height: 20px;width:30px"/><input type="button" style="background: -moz-linear-gradient(top,#ffffff,#e6e6e6);border: none" id='total_page' value="0 页" /></div></td></tr> </tbody> </table> <!-- 分页用按钮--> </div> </div> </div> </body> </html>
分页的核心jquery代码:
function getpages(pno,psize) { var num;//分页总行数 var totalpage = 0;//分页总页数 var pagesize = psize;//分页每行显示数 var currentpage = pno;//当前页 num = parseint(datas.length);//获取数据行数 if (num / pagesize > parseint(num / pagesize)) { totalpage = parseint(num / pagesize) + 1; } else { totalpage = parseint(num / pagesize); } var startrow = (currentpage - 1) * pagesize + 1;//开始显示的行 var endrow = currentpage * pagesize;//结束显示的行 endrow = (endrow > num) ? num : endrow; var tbody = jquery("#list_data>tbody"); tbody.empty(); jquery.each(datas, function (i, n) { var file = json.parse(n); if (startrow <= parseint(i + 1) && parseint(i + 1) <= endrow) { var row = createrow().appendto(tbody); //多选用,目前暂时未考虑 /* createcolumn().html("<input type='checkbox' id="+"fileid"+(i+1)+" name='fileid'/>").appendto(row);*/ createcolumn().text(i + 1).appendto(row); createcolumn().text(file.name).appendto(row); createcolumn().text(getsize(file.filesize)).appendto(row); var operationcolumn = createcolumn().appendto(row); } //每次执行分页代码时需要将前一次分页的判断结果清空 jquery("#last_page").removeattr("onclick"); jquery("#next_page").removeattr("onclick"); //当前页非第一页时 if (currentpage > 1) { jquery("#last_page").attr("onclick", "getpages(" + (parseint(currentpage) - 1) + "," + psize + ")"); } //当前页小于总页数时 if (currentpage < totalpage) { jquery("#next_page").attr("onclick", "getpages(" + (parseint(currentpage) + 1) + "," + psize + ")"); } //显示当前页码、总页数及生成跳转点击事件 jquery("#end_page").attr("onclick", "getpages(" + (totalpage) + "," + psize + ")"); jquery("#first_page").attr("onclick", "getpages(" + (1) + "," + psize + ")"); jquery("#jump_page").attr("onclick", "jumpage(" + (totalpage) + "," + psize + ")"); jquery("#total_page").val("/" + totalpage + " 页"); jquery("#page_no").val(currentpage); var btndownload = jquery("<button class='btn_download'>下载</button>"); var btndelete = jquery("<button class='btn_delete'>删除</button>"); //批量删除获取文件信息用,目前暂时不用 /*jquery("#"+"fileid"+(i+1)).attr("recordquery",json.stringify(recordquery));*/ btndownload.click(function () { location.href = "/download?filename=" + file.name; }); btndelete.click(function () { recordquery = jquery(this).attr("data-record-query"); var dialogdiv = jquery("<div></div>"); dialogdiv.dialog({ autoopen: false, modal: true, width: 500, position: {my: "center", at: "center", of: jquery(".content_wrapper_hidden")}, title: "文件删除", buttons: [ { text: "确认", click: function () { jquery.post("/delete", file.name, function (data) { location.reload(); }); jquery(this).dialog("close"); } }, { text: "取消", click: function () { jquery(this).dialog("close"); } } ] }); var text = "确认删除 "+ file.name + "?"; dialogdiv.text(text).dialog("open"); }); btndownload.appendto(operationcolumn); btndelete.appendto(operationcolumn); }); jquery(".btn_download,.btn_delete").button(); }
用于页面跳转的js代码:
//用于页码跳转方法 function jumpage(totalpage,psize){ var cpage=jquery("#page_no").val(); if(0< cpage && cpage <= totalpage){ getpages(cpage,psize); } else{ alert("out of range"); } }
计算文件的大小js:
function getsize(length) { var len, unit; if (length == 0) { len = 0; unit = "b"; } else if (length < 1024) { len = length; unit = "b"; } else if (length < (1024 * 1024)) { len = (length / 1024); unit = "kb"; } else { len = (length / 1024 / 1024); unit = "mb"; } return new number(len).tofixed(2) + unit; }
页面默认请求jquery:
//请求一次数据,然后存储到js变量中,保证只发送一条请求 var datas; jquery(function() { $.ajax({ type: "post", url: "/dopages", data: "{}", datatype: 'json', success: function(data) { datas = data; getpages(1,5); } }); });
项目中用到了便于生成table的自己编写的js工具:
function createcolumn() { return jquery("<td></td>"); } function createrow() { return jquery("<tr></tr>"); } function createele(tag){ return jquery("<"+tag+"></"+tag+">"); } function reload(){ window.location.reload(); } function tourl(url){ window.location.href=url; } function isstring(obj){ return typeof(obj) == "string"; } function isobject(obj){ return typeof(obj) == "object"; } function fillselect(select, data, valuekey, textkey){ var $select = isstring(select) ? jquery(select) : select; $select.empty(); jquery.each(data, function(i, item){ var value = (!isstring(item)) ? item[valuekey] : item; var text = (!isstring(item)) ? item[textkey] : item; var $op = createele("option").appendto($select); $op.text(text).val(value); }) } common.js
为了美观考虑,项目中引用了jquery ui:
代码.github:https://github.com/wenchaozou/jqueryforpages
百度云链接:https://pan.baidu.com/s/1de5cj5n
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!