纯jQuery实现前端分页功能
由于之前⾃⼰做过jquery分页,就是调⽤jni接⼝时,只能⽤前台分页解决显⽰问题。最近看到有⼈提这样的问题:⼀个请求传过来上万个数据怎么办?于是萌⽣了写这篇博客的想法。效果展⽰:
因为核⼼代码主要在前端jquery,为了简便,后台就⽤servlet遍历本地磁盘⽬录⽂件的形式模拟响应的数据。
本项⽬的⽬录结构:
本项⽬的本地遍历⽂件夹结构:
处理显⽰请求的servlet:
package com.action;
import com.alibaba.fastjson.JSON;
ity.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
*@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 Class().getResource("/fileroot.properties").getPath())); props.load(in);
String rootPath = Property("Root");
List fileList = new ArrayList();
File file = new File(rootPath);
File []files = file.listFiles();
Downloadfile df = new Downloadfile();
for(File f:files) {
df.Name());
df.String(f.length()));
System.out.Name());
fileList.JSONString(df));
}
resp.addHeader("Content-type","application/json");
resp.setHeader("content-type", "text/html;charset=UTF-8");
}
}
PagesServlet
处理下载⽂件请求的servlet:
package com.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.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 Class().getResource("/fileroot.properties").getPath())); props.load(in);
String rootPath = Property("Root");
String name = Parameter("filename");
name = new Bytes("ISO8859-1"),"UTF-8");
System.out.println(name);
//处理请求
//读取要下载的⽂件
File f = new File(rootPath+"\\"+ name);
ists()){
FileInputStream fis = new FileInputStream(f);
String filename=Name(),"utf-8"); //解决中⽂⽂件名下载乱码的问题
byte[] b = new byte[fis.available()];
/
/解决中⽂⽂件名下载后乱码的问题
resp.setContentType("application/x-msdownload");
resp.setHeader("Content-Disposition", "attachment;filename="+
new Bytes("utf-8"),"ISO-8859-1"));
//获取响应报⽂输出流对象
ServletOutputStream out =OutputStream();
//输出
out.write(b);
out.flush();
out.close();
}
}
}
DownloadFile
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="/xml/ns/javaee"
xmlns:xsi="/2001/XMLSchema-instance"
xsi:schemaLocation="/xml/ns/javaee /xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>PageServlet</servlet-name>
<servlet-class>com.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.action.DownloadFile</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DownServlet</servlet-name>
<url-pattern>/download</url-pattern>
</servlet-mapping>
</web-app>
前台完整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">
<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");
}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");
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) {
});
jQuery(this).dialog("close");
}
},
{
text: "取消",
click: function () {
jQuery(this).dialog("close");
}
}
]
});
var text = "确认删除 "+ file.name + "?";
<(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;
} 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" >
<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" >
<tbody align="center" valign="middle">
<tr><td><div id="pagination">
<!-- 全选和批量删除按钮,⽬前暂时未考虑-->
<!--<input type="button" id='fileIds' value="全选"/><input type="button" id='delete_fileIds' value <input type="button" id='first_page' value="⾸页"/><input type="button" id='last_page' value= <input autocomplete="off" class="ui-autocomplete-input" id="page_no" /><input type="button" 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");
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) {
});
jQuery(this).dialog("close");
}
},
{
click: function () {
jQuery(this).dialog("close");
}
}
]
});
var text = "确认删除 "+ file.name + "?";
<(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(){
load();
}
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;
$pty();
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:
以上就是本⽂的全部内容,希望本⽂的内容对⼤家的学习或者⼯作能带来⼀定的帮助,同时也希望多多⽀持!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论