1.官网教程链接:http://www.datatables.net/
2.基础使用可参考他人博客链接:http://blog.csdn.net/mickey_miki/article/details/8240477,这个网址上的信息很全。
3.自己碰到的问题(本人后台使用Java开发):
Question1:datatables 可以实现实时搜索数据列表,可如何将参数传入后台?(请查看思路和代码)
(1)设置searching: true,
(2)获取搜索输入框的value值,在ajax的data属性传入参数,并注意前后台配置的参数名必须保持一致
(3)如果传入后台的数据为乱码,需先进行转码处理。
思路图:
Question2: 下拉框页长为ALL时,后台处理数据的方法?
后台主要获取的三个参数: draw是请求的序号,start是数据的偏移量,length是需要返回的最大数据条数;当length = -1时,程序直接执行查询全部用户,不执行带有分页器的代码。
前端页面的参数:draw: 表示请求次数,recordsTotal: 总记录数,recordsFiltered: 过滤后的总记录数,data: 具体的数据对象数组
Question3: Datatables列排序,后台传递的参数是什么?
order[0][column]: 二维表格,而只有一维需要排序,是第一行列名的位置;所以 order 的下标为0. 该属性表示第几列需要排序。
order[0][dir]: 排序方式 ASC | DESC
前台:设置"ordering" : true,
后台的获取代码如下:(不需要像length、start等参数通过在方法中传递)
4.个人使用的基本属性
- “columns":[{"data": "functionurl"},{},{}] 注:初始化列,该属性为对象数组,不需要定义的列也需要用null进行占位,functionurl字段是与数据库的字段一致
- “columnsDefs”:[{"render":funtion(){}, "targets":4}] 注:和columns相似,但可用targets灵活指定列, render是通过函数根据个人需求随意改变内容值。
Example One:将修改、删除按钮放在列中显示
"columnDefs" : [ { "orderable": false, "render" : function(data, type, row) { var buttons = ‘‘; buttons +="<a href=‘javascript:void(0);‘ onClick=\"handle_ed(‘" + row.id + "‘)\" ><i class=‘Hui-iconfont‘></i><i class=‘im-pencil2‘></i></a>"; buttons +=" <a href=‘javascript:void(0);‘ onClick=\"function_del(‘one‘,‘" + row.id + "‘)\" ><i class=‘Hui-iconfont‘></i></a>"; return buttons; }, "targets" : 4, } ]
效果图:
Example Two: 数据库的字段数据为1或者2,而页面根据判断显示是或者否
"render": function(data, type, row) { var flag = ‘‘; if( row.systemflag == 1){ flag = "是"; } if( row.systemflag == 2){ flag = "否"; } return flag; },
方法中参数含义: data: 当前单元格的数据;type: 当前列的类型;row: 当前行完整的数据对象;meta: 为一个子对象,包含3个属性;
row: 当前行的索引; col: 当前列的索引; settings: 当前DataTables控件的settings对象
- 刷新页面:table.fnDraw(); 网上资料有的人都写table.draw(),但是在我这里会产生提示错误table.draw() is not a function, 查看源码时,可以这样用 table.api().search($(this).val()).draw(); //Here table is instance of datatable.
5.不规范书写造成错误范例
错误提示原因可能是逗号缺少,列的属性不一致,指定列的下标错误(本来有五列,确指定第六列)
6.扩展工具(列显示/隐藏、Excel、Print)
(1)列显示/隐藏
页面引入:CSS <!-- columns show and hide css style -->
<link href="../../static/datatables/css/buttons/buttons.dataTables.min.css" rel="stylesheet" type="text/css" />
<link href="../../static/datatables/css/admin/jquery.dataTables.css" rel="stylesheet" type="text/css" />
JS <!-- buttons hide and show -->
//此处的JS文件一定要放在名为1.10.8的文件夹下,否则会提示错误:这个可能需要1.10.8或者更高版本。
<script type="text/javascript" src="lib/datatables/1.10.8/jquery.dataTables.js"></script>
<script type="text/javascript" src="../../static/datatables/js/buttons/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="../../static/datatables/js/buttons/buttons.colVis.min.js"></script>
配置dom节点: "dom" : ‘Blfrtip‘,
配置buttons属性:
"buttons": [ {
extend: ‘colvis‘,
text: ‘列段显示/隐藏‘
},
]
(2)Excel
页面引入:<!-- excel export data-->
<script type="text/javascript" src="lib/datatables/js/excel/buttons.flash.min.js"></script> //此文件导出可以兼容IE9以上
/*如果是支持HTML5的则可以引入文件*/
<script type="text/javascript" src="lib/datatables/js/excel/jszip.min.js"></script>
<script type="text/javascript" src="lib/datatables/js/excel/buttons.html5.min.js"></script>
配置buttons属性:
"buttons": [ {
extend: ‘colvis‘,
text: ‘列段显示/隐藏‘
},{
extend: ‘excel‘
//extend: ‘excelHtml5‘ //支持html5导出设置
},
]
(3)Print
页面引入:<script type="text/javascript" src="../../static/bj/js/buttons/buttons.print.min.js"></script>
配置buttons属性:
"buttons": [ {
extend: ‘colvis‘,
text: ‘列段显示/隐藏‘
},{
extend: ‘excel‘
//extend: ‘excelHtml5‘ //支持html5导出设置
},{
extend: ‘print‘,
text: ‘打印‘,
exportOptions: {
//columns: ‘:visible‘
}
},
]
(4)列拖拽与列宽拖动
页面引入: <!-- column moving script -->
<script type="text/javascript" src="lib/datatables/js/ColReorder/colResizable-1.5.min.js"></script>
<script type="text/javascript" src="lib/datatables/js/ColReorder/dataTables.colReorder.js"></script>
配置:/*在datatables()方法声明之外插入下面代码*/
//columns moving
new $.fn.dataTable.ColReorder( table, {
// options
} );
//使用col插件实现表格头宽度拖拽
$(".table").colResizable();
7.下面是实现的整体代码
前台代码:
1 <%@ page language="java" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%> 2 <!DOCTYPE HTML> 3 <html> 4 <head> 5 <meta charset="utf-8"> 6 <meta name="renderer" content="webkit|ie-comp|ie-stand"> 7 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 8 <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" /> 9 <meta http-equiv="Cache-Control" content="no-siteapp" /> 10 <LINK rel="Bookmark" href="/favicon.ico" > 11 <LINK rel="Shortcut Icon" href="/favicon.ico" /> 12 13 <!-- columns show and hide css style --> 14 <link href="../../static/datatables/css/buttons/buttons.dataTables.min.css" rel="stylesheet" type="text/css" /> 15 <link href="../../static/datatables/css/admin/jquery.dataTables.css" rel="stylesheet" type="text/css" /> 16 17 <link rel="stylesheet" type="text/css" href="../../static/h-ui/css/H-ui.min.css" /> 18 <link rel="stylesheet" type="text/css" href="../../static/h-ui.admin/css/H-ui.admin.css" /> 19 <link rel="stylesheet" type="text/css" href="../../static/Hui-iconfont/1.0.7/iconfont.css" /> 20 <link rel="stylesheet" type="text/css" href="../../static/icheck/icheck.css" /> 21 <link rel="stylesheet" type="text/css" href="../../static/h-ui.admin/skin/default/skin.css" id="skin" /> 22 <link rel="stylesheet" type="text/css" href="../../static/h-ui.admin/css/style.css" /> 23 24 <title>用户管理</title> 25 </head> 26 <body> 27 <nav class="breadcrumb"><i class="Hui-iconfont"></i> 首页 <span class="c-gray en">></span> 用户中心 <span class="c-gray en">></span> 用户管理 28 <a class="btn btn-success radius r mr-20" style="line-height:1.6em;margin-top:3px" href="javascript:void(0);" onclick="reloadTable()" title="刷新" ><i class="Hui-iconfont"></i></a></nav> 29 <div class="pd-20"> 30 <div class="text-c"> 31 <select class="input-text" style="width:150px;height:30px" id="btnSelected"> 32 <option value="1">菜单名称</option> 33 </select> 34 35 <input type="text" class="input-text" style="width:250px" placeholder="输入关键字" id="keysearch" name=""> 36 <button type="submit" class="btn btn-success radius" id="btnSearch" name=""><i class="Hui-iconfont"></i> 查询</button> 37 </div> 38 <div class="cl pd-5 bg-1 bk-gray mt-20"> 39 <span class="l"> 40 <a href="javascript:void(0);" onclick="delall()" class="btn btn-danger radius"><i class="Hui-iconfont"></i> 批量删除</a> 41 <a href="javascript:void(0);" onclick="handle_add()" class="btn btn-primary radius"><i class="Hui-iconfont"></i> 添加功能</a> 42 </span> 43 </div> 44 <div class="mt-20"> 45 <table class="table table-border table-bordered table-hover table-bg table-sort"> 46 <thead> 47 <tr class="text-c"> 48 <th ><input type="checkbox" id="checkbox">全选/反选</th> 49 <th>菜单名称</th> 50 <th>菜单地址</th> 51 <th>是否是系统菜单</th> 52 <th>操作</th> 53 </tr> 54 </thead> 55 56 </table> 57 </div> 58 </div> 59 60 <script type="text/javascript" src="../../static/jquery/1.9.1/jquery.min.js"></script> 61 <script type="text/javascript" src="../../static/layer/2.1/layer.js"></script> 62 <script type="text/javascript" src="../../static/laypage/1.2/laypage.js"></script> 63 <script type="text/javascript" src="../../static/My97DatePicker/WdatePicker.js"></script> 64 <script type="text/javascript" src="../../static/h-ui/js/H-ui.js"></script> 65 <script type="text/javascript" src="../../static/h-ui.admin/js/H-ui.admin.js"></script> 66 <!-- <script type="text/javascript" src="../../static/datatables/1.10.0/jquery.dataTables.min.js"></script> --> 67 <!-- column moving script --> 68 <script type="text/javascript" src="../../static/datatables/js/admin/1.10.8/jquery.dataTables.js"></script> 69 <script type="text/javascript" src="../../static/datatables/js/admin/colResizable-1.5.min.js"></script> 70 <script type="text/javascript" src="../../static/datatables/ColReorder/js/dataTables.colReorder.js"></script> 71 <!-- buttons hide and show --> 72 <script type="text/javascript" src="../../static/datatables/js/buttons/dataTables.buttons.min.js"></script> 73 <script type="text/javascript" src="../../static/datatables/js/buttons/buttons.colVis.min.js"></script> 74 75 76 77 <script type="text/javascript"> 78 79 var table ; 80 $(function(){ 81 table = $(‘.table-sort‘).dataTable({ 82 "bServerSide" : true, 83 "bAutoWidth" : false, 84 "processing" : true, 85 "ordering" : true, 86 "bFilter": true, 87 "searching" : true, 88 "order": [[ 1, "desc" ]] , 89 "bPaginate" : true, 90 "lengthMenu": [ 91 [ 5, 10, 20, 30, 40, 50, -1 ], 92 [ 5, 10, 20, 30, 40, 50, "All"] 93 ], 94 "dom" : ‘Blfrtip‘, 95 "buttons": [ //for columns selective hide and show 96 { 97 extend: ‘colvis‘, 98 text: ‘列段显示/隐藏‘ 99 }, 100 /* { 101 extend: ‘excel‘ 102 103 }, 104 { 105 extend: ‘print‘, 106 text: ‘打印‘, 107 exportOptions: { 108 //columns: ‘:visible‘ 109 } 110 }, */ 111 ], 112 "ajax" : { 113 "url" : "/functionController/datagrid", 114 "data" : function(d) { 115 //real-time remote search params pass to server 116 var searchtext = $(".dataTables_wrapper .dataTables_filter input").val(); 117 if(searchtext != null){ 118 d.searchtext = encodeURI(searchtext); 119 } 120 //keywords search params pass to server 121 var sel = $(‘#btnSelected‘).val(); //columns name in selectbox 122 if(sel == 1){ 123 d.keysearch = encodeURI($(‘#keysearch‘).val()); 124 } 125 126 127 } 128 }, 129 "columns" : [{ 130 "data" : "" 131 }, { 132 "data" : "text" 133 }, { 134 "data" : "functionurl" 135 }, { 136 "data" : "systemflag" 137 }, { 138 "data" : "" 139 } ], 140 "columnDefs" : [ 141 { 142 "orderable": false, 143 "render" : function(data, type, row) { 144 var buttons = ‘‘; 145 buttons +="<a href=‘javascript:void(0);‘ onClick=\"handle_ed(‘" + row.id + "‘)\" ><i class=‘Hui-iconfont‘></i><i class=‘im-pencil2‘></i></a>"; 146 buttons +=" <a href=‘javascript:void(0);‘ onClick=\"function_del(‘one‘,‘" + row.id + "‘)\" ><i class=‘Hui-iconfont‘></i></a>"; 147 return buttons; 148 }, 149 "targets" : 4, 150 }, 151 { 152 "sWidth": "95px", 153 "orderable": false, 154 "render" : function(data, type, row) { 155 var buttons = ‘‘; 156 buttons += "<input type=‘checkbox‘ value=‘" + row.id + "‘ name=‘checkList‘>"; 157 return buttons; 158 }, 159 "targets" : 0, 160 }, 161 { 162 "render": function(data, type, row) { 163 var flag = ‘‘; 164 if( row.systemflag == 1){ 165 flag = "是"; 166 } 167 return flag; 168 }, 169 "targets" :3, 170 "bSearchable":true 171 172 }], 173 "language" : { 174 "url" : "../../static/datatables/i18n/Chinese.json" 175 } 176 }); 177 178 //columns moving 179 new $.fn.dataTable.ColReorder( table, { 180 // options 181 } ); 182 //使用col插件实现表格头宽度拖拽 183 $(".table").colResizable(); 184 185 }); 186 /*单条件查询*/ 187 $(‘#btnSearch‘).on(‘click‘, function(){ 188 table.fnDraw(); 189 }); 190 191 /*添加*/ 192 function handle_add(){ 193 layer.open({ 194 type: 2, 195 title: ‘新增功能‘, 196 area: [‘500px‘,‘360px‘], 197 offset: ‘50px‘, 198 maxmin: true, 199 content: ‘${pageContext.request.contextPath}/functionController/toFunctionAddPage‘, 200 end: function(){ 201 table.fnDraw(); 202 } 203 }); 204 } 205 206 /**全选、反选**/ 207 $("#checkbox").click( 208 function () { 209 if (this.checked) { 210 $("input[name=‘checkList‘]").each(function () { 211 this.checked = true; 212 }); 213 } else { 214 $("input[name=‘checkList‘]").each(function () { 215 this.checked = false; 216 }); 217 } 218 } 219 ); 220 221 /*编辑*/ 222 function handle_ed(id){ 223 layer.open({ 224 type: 2, 225 title: [‘编辑功能‘, ‘font-size:18px‘], 226 shadeClose: true, 227 offset: ‘50px‘, 228 content: ‘/functionController/toFunctionEditPage?id=‘+id, 229 shif: 2, 230 maxmin: true, 231 area: [‘490px‘,‘360px‘], 232 end: function(){ 233 table.fnDraw(); 234 } 235 }); 236 } 237 238 /*刷新**/ 239 function reloadTable(){ 240 layer.msg("刷新成功"); 241 table.fnDraw(); 242 } 243 244 //Delete multiple data 245 function delall(){ 246 var str = ‘‘; 247 $("input[name=‘checkList‘]:checked").each(function (i, o) { 248 str += $(this).val(); 249 str += ","; 250 }); 251 function_del("many",str); 252 } 253 /**删除数据行**/ 254 function function_del(flag,id) { 255 256 var count=0; 257 var str = ‘‘; 258 $("input[name=‘checkList‘]:checked").each(function (i, o) { 259 str += $(this).val(); 260 str += ","; 261 count++; 262 }); 263 264 if (str.length > 0 || id.length > 0) { 265 266 if(flag == "one"){ 267 if (count>1) { 268 layer.msg("单行删除,不支持多选"); 269 return; 270 } 271 } 272 var msg =‘‘; 273 if(count == 0 ){ 274 msg = "您确定删除此菜单吗?"; 275 }else{ 276 if(flag == "one"){ 277 msg = "您确定删除此菜单吗?"; 278 }else{ 279 msg = "您确定删除"+count+"个菜单吗?"; 280 } 281 } 282 if (!confirm(msg)) { 283 return; 284 } 285 var ids = str.substr(0, str.length - 1); 286 $.ajax({ 287 dataType: ‘json‘, 288 type: ‘post‘, 289 cache: false, 290 url: ‘/functionController/remove‘, 291 data: { 292 ids: id ? id : ids, 293 }, 294 async: false, 295 success: function (data) { 296 layer.msg(data.msg); 297 table.fnDraw(); 298 } 299 }); 300 } else { 301 layer.msg("至少选择一条记录操作"); 302 } 303 } 304 </script> 305 </body> 306 </html>
后台代码:
1 @RequestMapping("/datagrid") 2 @ResponseBody 3 public JSONObject allMenu(Ts_Function tmenu,String keysearch, String searchtext, String draw,String start,String length,HttpServletRequest request) { 4 Map map = new HashMap();//条件存储 5 JSONObject jsonObject = new JSONObject(true); 6 JSONArray jsonArray = new JSONArray(); 7 List<HashMap<String, Object>> tmenuList; 8 String tt = ""; 9 10 //obtain the order params {order: column number; dir: desc/asc; orderColumn: column name 11 String order=request.getParameter("order[0][column]"); 12 String dir=request.getParameter("order[0][dir]"); 13 String orderColumn = request.getParameter("columns["+order+"][data]"); 14 15 map.put("dir", dir); 16 map.put("orderColumn", orderColumn); 17 18 if(Integer.valueOf(length) != -1){ 19 int page=0; 20 int row= Integer.valueOf(length == null ? "10":length); 21 if (null!=start && null!=length) { 22 page = Integer.valueOf(start) / Integer.valueOf(length) + 1; 23 } else { 24 page = 1; 25 row = 10; 26 } 27 PageHelper.startPage(page, row); 28 if(searchtext !=null){ 29 searchtext =URLDecoder.decode(searchtext, "utf-8"); 30 if(searchtext.equals("是")){ 31 searchtext = "1"; 32 } 33 map.put("searchtext", searchtext); 34 } 35 //keywords search 36 if(keysearch !=null){ 37 keysearch =URLDecoder.decode(keysearch, "utf-8"); 38 map.put("keysearch", keysearch); 39 } 40 tmenuList = menuService.selectAll(map); 41 Page pageInfo = (Page) tmenuList; 42 jsonObject.put("draw",draw); 43 jsonObject.put("recordsTotal", pageInfo.getTotal()); 44 jsonObject.put("recordsFiltered",pageInfo.getTotal()); 45 }else{ 46 if(searchtext !=null){ 47 tt =URLDecoder.decode(searchtext, "utf-8"); 48 if(tt.equals("是")){ 49 tt = "1"; 50 } 51 } 52 if(keysearch !=null){ 53 keysearch =URLDecoder.decode(keysearch, "utf-8"); 54 map.put("keysearch", keysearch); 55 } 56 tmenuList = menuService.selectAll(map); 57 58 jsonObject.put("draw",draw); 59 jsonObject.put("recordsTotal", tmenuList.size()); 60 jsonObject.put("recordsFiltered", tmenuList.size()); 61 } 62 63 64 for(Map<String, Object> temp : tmenuList) 65 { 66 JSONObject info = new JSONObject(); 67 //放入页面需要展示的值 68 info.put("id",temp.get("id")); 69 info.put("text",temp.get("text")); 70 info.put("functionurl",temp.get("functionurl")); 71 info.put("systemflag",temp.get("systemflag")); 72 jsonArray.add(info); 73 } 74 jsonObject.put("data",jsonArray); 75 76 return jsonObject; 77 }
代码中的Page 和PageHelper的引用代码:import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;