如何使用纯jQuery实现前端分页功能
这篇文章给大家分享的是有关如何使用纯jQuery实现前端分页功能的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
专注于为中小企业提供成都网站设计、网站建设服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业义安免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了上1000家企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。
效果展示:
因为核心代码主要在前端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配置:
web.xml PageServlet com.cn.action.PagesServlet PageServlet /doPages DownServlet com.cn.action.DownloadFile DownServlet /download
前台完整html代码:
Num Files Size Operation
分页的核心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("").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(""); var btnDelete = jQuery(""); //批量删除获取文件信息用,目前暂时不用 /*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(""); 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(""); } function createRow() { return jQuery(" "); } 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实现前端分页功能”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
文章题目:如何使用纯jQuery实现前端分页功能
浏览地址:http://myzitong.com/article/jesigc.html