纯Jquery前端分页
---恢复内容开始---
由于之前自己做过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="stylesheet"> <link href="/resource/css/css.css" 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
计算文件的大小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; }
计算文件大小js
页面默认请求jquery:
//请求一次数据,然后存储到js变量中,保证只发送一条请求 var datas; jQuery(function() { $.ajax({ type: "POST", url: "/doPages", data: "{}", dataType: 'json', success: function(data) { datas = data; getPages(1,5); } }); });
请求jquery
项目中用到了便于生成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/1kVNWVOV 密码: nq55
---恢复内容结束---
纯Jquery前端分页的更多相关文章
- Jquery前端分页插件pagination同步加载和异步加载
上一篇文章介绍了Jquery前端分页插件pagination的基本使用方法和使用案例,大致原理就是一次性加载所有的数据再分页.https://www.jianshu.com/p/a1b8b1db025 ...
- 纯JS前端分页方法(JS分页)
1.JS分页函数:开发过程中,分页功能一般是后台提供接口,前端只要传page(当前页码)和pageSize(每页最大显示条数)及对应的其他查询条件,就可以返回所需分页显示的数据. 但是有时也需要前端本 ...
- jQuery插件实例六:jQuery 前端分页
先来看看效果: 对于前端分页,关键是思路,和分页算法.本想多说两句,可又觉得没什么可说的,看代码吧: 如何使用? $("#pging").zPagination({ 'navEve ...
- Jquery前端分页插件pagination使用
插件描述:JqueryPagination是一个轻量级的jquery分页插件.只需几个简单的配置就可以生成分页控件.并且支持ajax获取数据,自定义请求参数,提供多种方法,事件和回调函数,功能全面的分 ...
- js前端分页之jQuery
锋利的js前端分页之jQuery 大家在作分页时,多数是在后台返回一个导航条的html字符串,其实在前端用js也很好实现. 调用pager方法,输入参数,会返回一个导航条的html字符串.方法的内部比 ...
- 前端分页神器,jquery grid的使用(前后端联调),让分页变得更简单。
jquery grid 是一款非常好用的前端分页插件,下面来讲讲怎么使用. 首先需要引入jquery grid 的CSS和JS (我们使用的是bootstrap的样式) 下面我们通过一个例子来讲解,需 ...
- 基于vue2.0实现仿百度前端分页效果(一)
前言 最近在接手一个后台管理项目的时候,由于之前是使用jquery+bootstrap做的,后端使用php yii框架,前后端耦合在一起,所以接手过来之后通过vue进行改造,但依然继续使用的boots ...
- EasyUI表格DataGrid前端分页和后端分页的总结
Demo简介 Demo使用Java.Servlet为后台代码(数据库已添加数据),前端使用EasyUI框架,后台直接返回JSON数据给页面 1.配置Web.xml文件 <?xml version ...
- Jeasyui的datagrid前端分页要点
Jeasyui的分页有两种方式: 1. 服务器端分页,是真正的分页,datagridview的pager会自动把pageSize和pageNum传到后台,后台根据根据pageSize和pageNum构 ...
随机推荐
- IIS 之 在IIS7、IIS7.5中应用程序池最优配置方案
找到Web站点对应的应用程序池,"应用程序池" → 找到对应的"应用程序池" → 右键"高级设置..." 一.一般优化方案 1.基本设置 [ ...
- matlab 利用while循环计算平均值和方差
一.该程序是用来测输入数据的平均值和方差的 公式: 二. 项目流程: 1. State the problem假定所有测量数为正数或者0,计算这一系列测量数的平均值和方差.假定我们预先不知道有多少测量 ...
- nginx配合IIS实现简单负载均衡
1.IIS 部署两个站点端口分别为8081和8082 8081站点和8082站点如下[随便写了个没有样式的很丑的页面],我特意加了111和222区分 2.设置nginx配置文件,实现简单的负载 ...
- c++编程思想(一)--对象导言
回过头来看c++编程思想第一章,虽然只是对c++知识的一个总结,并没有实质性知识点,但是收获还是蛮多的! 下面感觉是让自己茅塞顿开的说法,虽然含义并不是很准确,但是很形象(自己的语言): 1.类描述了 ...
- 【Java深入研究】2、JVM类加载机制
一.先看看编写出的代码的执行过程: 二.研究类加载机制的意义 从上图可以看出,类加载是Java程序运行的第一步,研究类的加载有助于了解JVM执行过程,并指导开发者采取更有效的措施配合程序执行. 研究类 ...
- 【译文】用Spring Cloud和Docker搭建微服务平台
by Kenny Bastani Sunday, July 12, 2015 转自:http://www.kennybastani.com/2015/07/spring-cloud-docker-mi ...
- 在SQL Server里如何处理死锁
在今天的文章里,我想谈下SQL Server里如何处理死锁.当2个查询彼此等待时会发生死锁,没有一个查询可以继续它们的操作.首先我想给你大致讲下SQL Server如何处理死锁.最后我会展示下SQL ...
- Asp.Net MVC学习总结(二)——控制器与动作(Controller And Action)
一.理解控制器 1.1.什么是控制器 控制器是包含必要的处理请求的.NET类,控制器的角色封装了应用程序逻辑,控制器主要是负责处理请求,实行对模型的操作,选择视图呈现给用户. 简单理解:实现了ICon ...
- MINA、Netty、Twisted一起学(十一):SSL/TLS
什么是SSL/TLS 不使用SSL/TLS的网络通信,一般都是明文传输,网络传输内容在传输过程中很容易被窃听甚至篡改,非常不安全.SSL/TLS协议就是为了解决这些安全问题而设计的.SSL/TLS协议 ...
- Mac上写C++
用惯Windows的同学可能刚开始用Mac的时候并不知道如何写C++,我刚开始在Mac上写C++的时候也遇到过这个困扰,Mac上并没有Windows上自己用习惯的Visual C++,下面我分享一下个 ...