纯jQuery实现前端分页功能


Posted in jQuery onMarch 23, 2017

由于之前自己做过jquery分页,就是调用jni接口时,只能用前台分页解决显示问题。最近看到有人提这样的问题:一个请求传过来上万个数据怎么办?于是萌生了写这篇博客的想法。

效果展示:

纯jQuery实现前端分页功能

因为核心代码主要在前端jquery,为了简便,后台就用servlet遍历本地磁盘目录文件的形式模拟响应的数据。

本项目的目录结构:

纯jQuery实现前端分页功能

本项目的本地遍历文件夹结构:

纯jQuery实现前端分页功能

处理显示请求的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:

纯jQuery实现前端分页功能

代码.GitHub:https://github.com/Wenchaozou/JqueryForPages

百度云链接:https://pan.baidu.com/s/1dE5Cj5n

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持三水点靠木!

jQuery 相关文章推荐
jQuery日程管理控件glDatePicker用法详解
Mar 29 jQuery
解决jQuery ajax动态新增节点无法触发点击事件的问题
May 24 jQuery
jQuery之动画ajax事件(实例讲解)
Jul 18 jQuery
jQuery EasyUI的TreeGrid查询功能实现方法
Aug 08 jQuery
jQuery实现手势解锁密码特效
Aug 14 jQuery
使用jQuery 操作table 完成单元格合并的实例
Dec 27 jQuery
CSS3结合jQuery实现动画效果及回调函数的实例
Dec 27 jQuery
JQuery选中select组件被选中的值方法
Mar 08 jQuery
jquery 实现拖动文件上传加载进度条功能
Mar 18 jQuery
jquery ajaxfileuplod 上传文件 essyui laoding 效果【防止重复上传文件】
May 26 jQuery
jQuery实现输入框的放大和缩小功能示例
Jul 21 jQuery
jQuery实现购物车全功能
Jan 11 jQuery
JQuery 进入页面默认给已赋值的复选框打钩
Mar 23 #jQuery
jQuery插件FusionWidgets实现的AngularGauge图效果示例【附demo源码】
Mar 23 #jQuery
jQuery插件FusionWidgets实现的Bulb图效果示例【附demo源码下载】
Mar 23 #jQuery
jQuery插件FusionWidgets实现的Cylinder图效果示例【附demo源码】
Mar 23 #jQuery
jQuery插件Echarts实现的渐变色柱状图
Mar 23 #jQuery
jquery实现图片平滑滚动详解
Mar 22 #jQuery
jQuery轻松实现无缝轮播效果
Mar 22 #jQuery
You might like
php的chr和ord函数实现字符加减乘除运算实现代码
2011/12/05 PHP
php把大写命名转换成下划线分割命名
2015/04/27 PHP
PHP7新功能总结
2019/04/14 PHP
把textarea中字符串里含有的回车换行替换成&amp;lt;br&amp;gt;的javascript代码
2007/04/20 Javascript
Javascript创建自定义对象 创建Object实例添加属性和方法
2012/06/04 Javascript
jquery获取tr中控件值并操作tr实现思路
2013/03/27 Javascript
鼠标选择动态改变网页背景颜色的JS代码
2013/12/10 Javascript
Node.js安装教程和NPM包管理器使用详解
2014/08/16 Javascript
javascript函数命名的三种方式及区别介绍
2016/03/22 Javascript
微信小程序  audio音频播放详解及实例
2016/11/02 Javascript
BootStrap table删除指定行的注意事项(笔记整理)
2017/02/05 Javascript
Angular4 中内置指令的基本用法
2017/07/31 Javascript
详解webpack require.ensure与require AMD的区别
2017/12/13 Javascript
vue、react等单页面项目应该这样子部署到服务器
2018/01/03 Javascript
vue页面离开后执行函数的实例
2018/03/13 Javascript
利用aardio给python编写图形界面
2017/08/21 Python
python 将数据保存为excel的xls格式(实例讲解)
2018/05/03 Python
基于Django的乐观锁与悲观锁解决订单并发问题详解
2019/07/31 Python
Python实现数值积分方式
2019/11/20 Python
python 实现将list转成字符串,中间用空格隔开
2019/12/25 Python
详解python 破解网站反爬虫的两种简单方法
2020/02/09 Python
python实点云分割k-means(sklearn)详解
2020/05/28 Python
Flask-SocketIO服务端安装及使用代码示例
2020/11/26 Python
html5定制表单_动力节点Java学院整理
2017/07/11 HTML / CSS
阿迪达斯丹麦官网:adidas丹麦
2016/10/01 全球购物
美国女性运动零售品牌:Lady Foot Locker
2017/05/12 全球购物
美国最大的无人机经销商:DroneNerds
2018/03/20 全球购物
任课老师推荐信范文
2013/11/24 职场文书
教师应聘个人求职信
2013/12/10 职场文书
优秀驾驶员先进事迹材料
2014/05/04 职场文书
先进员工事迹材料
2014/12/20 职场文书
工作岗位职责范本
2015/02/15 职场文书
史上最牛辞职信
2015/05/13 职场文书
结婚仪式主持词
2015/06/29 职场文书
党员电教片《信仰》心得体会
2016/01/15 职场文书
MySQL索引失效场景及解决方案
2022/07/23 MySQL