JQuery Datatable用法
原文出处:http://sgyyz.blog.51cto.com/5069360/1408251
目标:
使用jQuery Datatable构造数据列表,并且增加或者隐藏相应的列,已达到数据显示要求。同时,jQuery Datatable强大的功能支持:排序,分页,搜索等。
Query Datatable能良好支持数据完全加载到本地后构建数据列表,排序、分页、搜索等功能就会自带,不需要我们去关心,在此主要说明通过后台动态的加载数据,已达到在大数据面前提高效率的效果。
1. 通过后台进行分页
2. 通过后台进行排序
3. 通过后台进行搜索
具体使用方法:
1. 首先构建我们需要的数据列表,以及页面显示表格。
1
2
3
4
5
6
7
8
9
10
|
< table id = "datatable" width = "100%" border = "1" >
< thead >
< tr >
< th >ID</ th >
< th >First Name</ th >
< th >Last Name</ th >
< th >Operation</ th >
</ tr >
< thead >
</ table >
|
表格建立很简单,只需用将表格定义好id,以及表头定义好。
2. 我们可以到jQuery Datatable官网上去下载一份jQuery和jQuery Datatable的js库。https://datatables.net/examples/server_side/simple.html。
3. 然后将这两个文件引入到页面文件中,注意jQuery的库一定要在最前面,因为页面加载的有顺序,保证后面的扩展库能使用到jQuery。同时,请下载最新的jQuery Datatable版本,因为它的写法以及参数更加简洁,功能更加多。【注:参数区别会在附录写明】
4. 编写前端代码。我们是要使用Ajax对后台进行请求,因此在配置datatable时,加上{"serverSide":true},已保证页面在加载时就请求后台,以及每次对datatable进行操作时也是请求后台。【附:如果想加上一点加载效果,可以增加{"processing": true}】。
配置请求后台URL:{"ajax": "load"}
5. 配置数据返回对应具体的列。在Datatable中,属性columns用来配置具体列的属性,包括对应的数据列名,是否支持搜索,是否显示,是否支持排序等。根据上述页面配置我们具体的列。如下:
1
2
3
4
5
6
7
8
9
10
11
12
|
$(document).ready( function () {
$( "#datatable" ).dataTable({
"processing" : true ,
"serverSide" : true ,
"ajax" : "load" ,
"columns" : [
{ "data" : "id" , "bSortable" : false },
{ "data" : "firstName" },
{ "data" : "lastName" }
]
});
});
|
第一列ID,设置为不允许排序。也可以增加不显示:{"visible": false}
6. 此时对于后台而言,返回的数据一定要按照一定规范。如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
{
"draw" : 2,
"recordsTotal" : 11,
"recordsFiltered" : 11,
"data" : [
{
"id" : 1,
"firstName" : "Troy" ,
"lastName" : "Young"
},
{
"id" : 2,
"firstName" : "Alice" ,
"lastName" : "LL"
},
{
"id" : 3,
"firstName" : "Larry" ,
"lastName" : "Bird"
}
// ......
]
}
|
参数解释:
draw:表示请求次数
recordsTotal:总记录数
recordsFiltered:过滤后的总记录数
data:具体的数据对象数组
7. 最后一列Operation,我们没有任何数据,用来放我们的通用操作列,如修改链接。 Datatable提供了自定义列columnDefs属性,他的值为数组对象,具体代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
$(document).ready( function () {
$( "#datatable" ).dataTable({
"processing" : true ,
"serverSide" : true ,
"ajax" : "load" ,
"columns" : [
{ "data" : "id" , "bSortable" : false },
{ "data" : "firstName" },
{ "data" : "lastName" }
],
"columnDefs" : [
{
"targets" : [3],
"data" : "id" ,
"render" : function (data, type, full) {
return "<a href='/update?id=" + data + "'>Update</a>" ;
}
}
]
});
});
|
targets:表示具体需要操作的目标列,下标从0开始
data: 表示我们需要的某一列数据对应的属性名
render:返回需要显示的内容。在此我们可以修改列中样式,增加具体内容
属性列表:data, 之前属性定义中对应的属性值
type, 未知
full, 全部数据值可以通过属性列名获取
具体效果图如下:
8. 我们再来看具体如何进行搜索、排序、分页。由于只是为了做demo,因此使用最简单的JDBC+Servlet的方式来实现。
首先我们来看,datatable给我们在做请求是传递过来的参数:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
=============== Request Paramerters ================
draw: 1
columns[ 0 ][data]: id
columns[ 0 ][name]:
columns[ 0 ][searchable]: true
columns[ 0 ][orderable]: true
columns[ 0 ][search][value]:
columns[ 0 ][search][regex]: false
columns[ 1 ][data]: firstName
columns[ 1 ][name]:
columns[ 1 ][searchable]: true
columns[ 1 ][orderable]: true
columns[ 1 ][search][value]:
columns[ 1 ][search][regex]: false
columns[ 2 ][data]: lastName
columns[ 2 ][name]:
columns[ 2 ][searchable]: true
columns[ 2 ][orderable]: true
columns[ 2 ][search][value]:
columns[ 2 ][search][regex]: false
order[ 0 ][column]: 0
order[ 0 ][dir]: asc
start: 0
length: 10
search[value]:
search[regex]: false
_: 1399345292266
=============== Request Paramerters ================
|
其中有用的数据就是start, length, order[0][column], order[0][dir], search[value]。具体参数意思:
start: 其实记录位置
length:页面显示数量
order[0][column]: 因为是二维的表格,因此只有一维需要排序,所以order的下标未0. 该属性表示第几列需要排序。
order[0][dir]: 排序方式ASC | DESC
search[value]: search输入框中的值
9. 这几个属性对后台进行排序、搜索、分页很有用。【注:因为是二维表,并且只是对一列进行操作,自然就是一维的,所以order下标始终为1。以后操作二维表有待研究。】
首先来看包含这几个功能的DAO层代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
/**
* This method includes the search, sort, pagination
* @param pageSize
* @param startRecord
* @param sortColumn
* @param sortDir
* @param searchValue
* @return
*/
public List<Data> loadDataList( int pageSize, int startRecord, String sortColumn, String sortDir, String searchValue) {
List<Data> results = new ArrayList<Data>();
StringBuffer sql = new StringBuffer( "select * from data " );
// for search
String[] columnsName = { "id" , "firstName" , "lastName" };
boolean searchAble = false ;
if (searchValue != null && ! "" .equals(searchValue)) {
sql.append( "where " );
searchAble = true ;
}
if (searchAble) {
StringBuffer temp = new StringBuffer();
for (String column : columnsName) {
temp.append( column+ " like '%" + searchValue + "%' or " );
}
sql.append(temp.substring( 0 , temp.length() - 3 ));
}
// for order
sql.append( " order by " + sortColumn + " " + sortDir + " " );
// for pagination
sql.append( " limit ?,? " );
System.out.println(sql.toString());
try {
stmt = conn.prepareStatement(sql.toString());
stmt.setInt( 1 , startRecord);
stmt.setInt( 2 , startRecord + pageSize);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
Data data = new Data();
data.setId(rs.getInt( 1 ));
data.setFirstName(rs.getString( 2 ));
data.setLastName(rs.getString( 3 ));
results.add(data);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return results;
}
|
DAO层中,统计代码类似,只用把分页和排序的SQL拼接去掉即可。
我们需要将我们的数据转换成JSON返回给前端,并且还要显示总记录数,过滤后总记录数。因此我们需要一个统一的类来将这些数据进行封装。由于在一个系统中不只一个对象需要展示到前端,因此统一的做一个为datatable封装类。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
package com.web.vo;
import java.util.List;
/**
* This VO used to generate the JSON data for data table, so please ensure that the attribute name is correct.
* If you want to define the fields name by yourself, please visit: https://datatables.net
* @author troyyang
*
* @param <T>
*/
public class DataVO<T> {
private int draw; // Client request times
private int recordsTotal; // Total records number without conditions
private int recordsFiltered; // Total records number with conditions
private List<T> data; // The data we should display on the page
// getter and setter method
}
|
万事具备,只欠前后交互代码。此处使用最简单的servlet。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
// For pagination
int pageSize = 10 ;
int startRecord = 0 ;
String size = request.getParameter( "length" );
if (! "" .equals(size) && size != null ) {
pageSize = Integer.parseInt(size);
}
String currentRecord = request.getParameter( "start" );
if (! "" .equals(currentRecord) && currentRecord != null ) {
startRecord = Integer.parseInt(currentRecord);
}
// For sortable
String sortOrder = request.getParameter( "order[0][column]" );
String sortDir = request.getParameter( "order[0][dir]" );
System.out.println( "sortOrder: " + sortOrder);
System.out.println( "sortDir: " + sortDir);
// For search
String searchValue = request.getParameter( "search[value]" );
int count = 0 ;
List<Data> results = new ArrayList<Data>();
count = dao.count();
results = dao.loadDataList(pageSize, startRecord, columnsName[Integer.parseInt(sortOrder)], sortDir, searchValue);
DataVO<Data> result = new DataVO<Data>();
result.setDraw(Integer.parseInt(request.getParameter( "draw" ) == null ? "0"
: request.getParameter( "draw" )) + 1 );
result.setData(results);
result.setRecordsTotal(count);
result.setRecordsFiltered(count);
Gson gson = new Gson();
String output = gson.toJson(result);
System.out.println( "Output JSON: \n" + output);
PrintWriter out = response.getWriter();
out.write(output);
out.flush();
out.close();
|
附录:
使用jQuery Datatable1.10之前的版本,必须使用sAjaxSource进行请求,但是请求数据和现在版本的请求数据不同,如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
=============== Request Paramerters ================
sEcho: 1
iColumns: 4
sColumns: ,,,
iDisplayStart: 0
iDisplayLength: 10
mDataProp_0: id
sSearch_0:
bRegex_0: false
bSearchable_0: true
bSortable_0: false
mDataProp_1: firstName
sSearch_1:
bRegex_1: false
bSearchable_1: true
bSortable_1: true
mDataProp_2: lastName
sSearch_2:
bRegex_2: false
bSearchable_2: true
bSortable_2: true
mDataProp_3: id
sSearch_3:
bRegex_3: false
bSearchable_3: true
bSortable_3: true
sSearch:
bRegex: false
iSortCol_0: 0
sSortDir_0: asc
iSortingCols: 1
_: 1399515247114
=============== Request Paramerters ================
|
转载于:https://www.cnblogs.com/ganbo/p/5227128.html
JQuery Datatable用法相关推荐
- JQuery dataTable 扩展+Ajax Post,Get一些基本操作(一)
首先, Asp.net MVC 系列暂时没有发现封装好的 类似于web form 的datagrid, 只有一款Jquery 的dataTable , 官网地址 http://www.datatabl ...
- jQuery Datatable 实用简单实例
目标: 使用jQuery Datatable构造数据列表,并且增加或者隐藏相应的列,已达到数据显示要求.同时,jQuery Datatable强大的功能支持:排序,分页,搜索等. Query Data ...
- 分享在MVC3.0中使用jQuery DataTable 插件
http://www.cnblogs.com/ryanding/archive/2011/02/18/1957318.html MVC3.0中使用JQuery.DataTable插件 http://b ...
- 如何使用JSON和Servlet创建JQuery DataTable
在本文中,我将介绍使用简单servlet传递的JSON创建JQuery DataTable所需的基本编码. DataTable是基于JQuery的非常强大的网格,具有高级功能,可以使用自定义功能在短时 ...
- jquery datatable 获取当前分页的数据
使用jquery datatable 遇到分页分别求和时,找了半天才找到获取当前分页数据的方法,以此总结 var table=$('#example').DataTable( {"pagin ...
- jquery datatable设置垂直滚动后,表头(th)错位问题
jquery datatable设置垂直滚动后,表头(th)错位问题 问题描述: 我在datatable里设置:"scrollY": '300px',垂直滚动属性后,表头的宽度就会 ...
- ajax会占用服务器端内存吗,javascript - 为什么不允许在jquery datatable服务器端处理ajax成功使用? - 堆栈内存溢出...
我正在使用asp.net mvc5并尝试使用jquery datatable插件服务器端处理. 服务器端处理的教程显示了从服务器返回结果的格式.但是我的项目的不同之处在于我无法从服务器发送" ...
- jQuery .tmpl() 用法
参考效果: DEMO 下载: jquery-tmpl-master 动态请求数据来更新页面是现在非常常用的方法,比如博客评论的分页动态加载,微博的滚动加载和定时请求加载等. 这些情况下,动态请求返回 ...
- MVC3.0中使用JQuery.DataTable插件。
最近做项目的时候发现了一个很好的JQuery插件DataTable但是网上相关的资料好像很少,本人英文不咋滴在官网上除了知道点哪能下载外其它就都不知道鸟.后来用了个把小时写了个小demo,分享给大家, ...
最新文章
- Python如何进行cross validation training
- 数据蒋堂 | BI系统中容易被忽视的数据源功能
- 「小程序JAVA实战」小程序的页面重定向(60)
- sqlserver附加数据库错误823的解决方案
- tableau必知必会之仪表板的最佳实践
- 布隆过滤器避免redis缓存穿透
- awb数据怎么计算_白平衡自己主动(AWB)算法---2,颜色计算
- 2020年上半年美团夜宵指数发展报告
- unef螺纹_硬料怎么车螺纹?一文了解螺纹的分类及其刀具选择
- 活动目录中组的类型和可用范围
- mysql主节点1593从节点正常_keepalived+双主架构
- tsql 和 clr 的性能实测比对
- linux离线卸载docker,Linux系统下Docker的安装与卸载
- php拍照虚线上传图片,照片怎么添加白色虚线 给照片上的人物周围添加虚线描边效果|照片处理工具...
- Vyos防火墙功能配置
- html情侣相册,浪漫的情侣相册名字
- java项目开发团队协作重要性_Java1班项目实战 | 团队协作,我们是认真的!
- 【题解】P2678 [NOIP2015 提高组] 跳石头
- 阿里大数据之路 总述
- python爬取歌曲_python爬取网易云音乐热歌榜实例代码
热门文章
- 还在用 BeanUtils来做对象转换吗?快试试 MapStruct吧
- Nginx + Spring Boot 实现负载均衡
- 12 个超燃的 IntelliJ IDEA 插件!
- 从Servlet、Dubbo、Mybatis聊聊责任链究竟怎么用
- Hinton团队CV新作:用语言建模做目标检测,性能媲美DETR
- 入门 | CNN也能用于NLP任务,一文简述文本分类任务的7个模型
- 2020年1月Github上最热门的开源项目
- 图神经网络(Graph Neural Networks,GNN)综述
- VS Code 成主宰、Vue 备受热捧!2019 前端开发趋势必读
- 漫画:什么是动态规划?