DataTable在项目中的应用
做web开发, 有的时候会用到表格,今天这里我将介绍一下DataTable, DataTable是一款jquery表格插件, 它是一个高度灵活的工具, 可以将任何HTML表格添加高级的交互功能,DataTable有如下优点:
分页, 即时搜索和排序
几乎支持任何数据源:DOM, Javascript,Ajax和服务器处理
支持不同的主题, DataTable, JQuery UI, Bootstrap
支持国际化
免费开源
下面我们来直接上例子吧:
那么在实际项目中我们可能有这样的需要,需要对表格数据进行搜索 分页 过滤等条件 接下来让我们一起开始DataTable的学习之旅吧
第一步:定义list.jsp:这里要记得引入jquery.js和dataTable.js文件
<script src="js/jQuery-2.2.0.min.js"></script>
<script src="js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
type:"GET",
url:"/datatable",
success:function(data){
},
error:function(data){}
})
})
</script>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th align="center">Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Ext</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
第二步: 后台的代码
@RequestMapping(value = "/datatable",method = RequestMethod.GET)
public ModelAndView list(){
logger.info("employee size:" + employeeList.size());
ModelAndView model = new ModelAndView();
model.addObject("employeeList", employeeList);
model.setViewName("datatable/list");
return model;
}
第三步: list.jsp文件做些修改, js部分代码就直接放在list.jsp中了
<%--
Created by IntelliJ IDEA.
User: jchen19
Date: 2016/3/31
Time: 9:43
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<link rel="stylesheet" href="css/jquery.dataTables.min.css">
<script src="js/jQuery-2.2.0.min.js"></script>
<script src="js/jquery.dataTables.min.js"></script>
<style>
tfoot input {
width: 100%;
padding: 3px;
box-sizing: border-box;
}
</style>
<html>
<head>
<title>datatable demo</title>
</head>
<body>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th align="center">Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<c:forEach items="${employeeList}" var="vs">
<tr>
<td align="center">${vs.name}</td>
<td align="center">${vs.position}</td>
<td align="center">${vs.office}</td>
<td align="center">${vs.extn}</td>
<td align="center">${vs.salary}</td>
</tr>
</c:forEach>
</tbody>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Ext</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
</body>
<script>
// $(function () {
// $("#example").DataTable({});
// });
$(document).ready(function(){
$('#example tfoot th').each( function () {
var title = $(this).text();
$(this).html( '<input type="text" placeholder="Search '+title+'" />' );
} );
var table = $('#example').DataTable();
// Apply the search
table.columns().every( function () {
var that = this;
$( 'input', this.footer() ).on( 'keyup change', function () {
if ( that.search() !== this.value ) {
that
.search( this.value )
.draw();
}
} );
} );
});
</script>
</html>
最终运行的结果就上图所示