datatable分页指南--前台分页和后台分页

来源:互联网 发布:游戏测试软件 编辑:程序博客网 时间:2024/05/07 18:12

 2977人阅读 评论(0) 收藏 举报
 分类:

一、介绍

Datatables是一款jQuery表格插件。它是一个高度灵活的工具,可以将任何HTML表格添加高级的交互功能。

  • 分页,即时搜索和排序
  • 几乎支持任何数据源:DOM, javascript, Ajax 和 服务器处理
  • 支持不同主题 DataTables, jQuery UI, Bootstrap, Foundation
  • 各式各样的扩展: Editor, TableTools, FixedColumns ……
  • 丰富多样的option和强大的API
  • 支持国际化
  • 超过2900+个单元测试
二、引入

[javascript] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <link rel="stylesheet" type="text/css" href="/DataTables-1.10.7/css/jquery.dataTables.css">  
  2.    
  3. <!-- jQuery -->  
  4. <script type="text/javascript" charset="utf8" src="/DataTables-1.10.0/js/jquery.js"></script>  
  5.    
  6. <!-- DataTables -->  
  7. <script type="text/javascript" charset="utf8" src="/DataTables-1.10.7/js/jquery.dataTables.js"></script>  

三、html

[javascript] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <table class="table table-bordered table-hover" id="bigDataList">  
  2.                <thead>  
  3.                <tr>  
  4.                  <th>  
  5.                    用户id  
  6.                  </th>  
  7.                  <th>  
  8.                    主叫  
  9.                  </th>  
  10.                  <th>  
  11.                    识别码  
  12.                  </th>  
  13.                  <th>  
  14.                    区域id  
  15.                  </th>  
  16.                  <th>  
  17.                    服务类型  
  18.                  </th>  
  19.                  <th>  
  20.                    服务组  
  21.                  </th>  
  22.                  <th>  
  23.                    位置区码  
  24.                  </th>  
  25.                  <th>  
  26.                    GPRS节点  
  27.                  </th>  
  28.                  <th>  
  29.                    分配记数  
  30.                  </th>  
  31.                  <th>  
  32.                    协议类型  
  33.                  </th>  
  34.                  <th>  
  35.                    开始时间  
  36.                  </th>  
  37.                  <th>  
  38.                    结束时间  
  39.                  </th>  
  40.                </tr>  
  41.                </thead>  
  42.                <tbody>  
  43.   
  44.                </tbody>  
  45.              </table>  

四、js代码

[javascript] view plain copy
 在CODE上查看代码片派生到我的代码片
  1.  var table1;  
  2.   
  3.       //dataTable初始化对象  
  4.       function bigDataTable(queryData){  
  5.         table1= $('#bigDataList').DataTable({  
  6.           "paging"true,  
  7.           "lengthChange"true,  
  8.           "searching"true,  
  9.           "ordering"true,  
  10.           "aaSorting" : [[0, "asc"]], //默认的排序方式,第1列,升序排列  
  11.           "info"true,  
  12.           "autoWidth"false,  
  13.           "destroy":true,  
  14.           "processing":true,  
  15.           "scrollX"true,   //水平新增滚动轴  
  16. //          "serverSide":true,    //true代表后台处理分页,false代表前台处理分页  
  17.           "aLengthMenu":[10,15,20],  
  18.           "PaginationType" : "full_numbers"//详细分页组,可以支持直接跳转到某页  
  19.           //当处理大数据时,延迟渲染数据,有效提高Datatables处理能力  
  20.           "deferRender"true,  
  21.           "ajax":{  
  22.             url:"getJson_BigData_queryDataByParams",  
  23.             dataSrc:  
  24.                     function(data){  
  25.                       if(data.callbackCount==null){  
  26.                         data.callbackCount=0;  
  27.                       }  
  28.                       //抛出异常  
  29.                       if(data.sqlException){  
  30.                         alert(data.sqlException);  
  31.                       }  
  32.                       //查询结束取消按钮不可用  
  33.                       $("#queryDataByParams").removeAttr("disabled");  
  34.                       return data.dataList;             //自定义数据源,默认为data  
  35.                     },     //dataSrc相当于success,在datatable里面不能用success方法,会覆盖datatable内部回调方法  
  36.             type:"post",  
  37.             data:queryData  
  38.           },  
  39.           columns:[  
  40.             { data: 'user_ip' },  
  41.             { data: 'calling'},  
  42.             { data: 'imei' },  
  43.             { data: 'cell_id'},  
  44.             { data: 'service_type' },  
  45.             { data: 'service_group'},  
  46.             { data: 'lac' },  
  47.             { data: 'sgsn'},  
  48.             { data: 'assignment_count' },  
  49.             { data: 'proto_type'},  
  50.             { data: 'start_time' },  
  51.             { data: 'end_time'},  
  52.           ],  
  53.   
  54.           /*是否开启主题*/  
  55.           "bJQueryUI"true,  
  56.           "oLanguage": {    // 语言设置  
  57.             "sLengthMenu""每页显示 _MENU_ 条记录",  
  58.             "sZeroRecords""抱歉, 没有找到",  
  59.             "sInfo""从 _START_ 到 _END_ /共 _TOTAL_ 条数据",  
  60.             "sInfoEmpty""没有数据",  
  61.             "sInfoFiltered""(从 _MAX_ 条数据中检索)",  
  62.             "sZeroRecords""没有检索到数据",  
  63.             "sSearch""检索:",  
  64.             "oPaginate": {  
  65.               "sFirst""首页",  
  66.               "sPrevious""前一页",  
  67.               "sNext""后一页",  
  68.               "sLast""尾页"  
  69.             }  
  70.           },  
  71.         });  
  72.       }  

点击请求ajax,返回渲染数据:

[javascript] view plain copy
 在CODE上查看代码片派生到我的代码片
  1.  //点击查询  
  2.       $("#queryDataByParams").on("click",function() {  
  3.         var reg = new RegExp("^[0-9]*$");  
  4.         var startTime=$("#searchDateRange").val().substring(0,19).replace(/-/g, '/');  
  5.         var endTime=$("#searchDateRange").val().substring(22,41).replace(/-/g, '/');  
  6.         var date1=new Date(startTime);  //开始时间  
  7.         var date2=new Date(endTime);    //结束时间  
  8.   
  9.         var date3=date2.getTime()-date1.getTime()  //时间差的毫秒数  
  10.         if(date3>60*60*24*1000){  
  11.           alert("开始时间与结束时间间隔大于24小时!");  
  12.           return false;  
  13.         }  
  14.         if(!$("#searchDateRange").val() || $("#searchDateRange").val()=="填写时间段"){  
  15.           alert("时间区段不能为空!");  
  16.           return false;  
  17.         }  
  18.         if(!$("#calling").val() && !reg.test($("#calling").val())){  
  19.           alert("请输入全数字!");  
  20.         }  
  21.         //查询时候设置按钮不可用  
  22.         $("#queryDataByParams").attr("disabled"true);  
  23.         var queryData={"startseg":$("#searchDateRange").val(),  
  24.           "callseg":$("#calling").val(),  
  25.           "identifiCode":$("#identifiCode").val(),  
  26.           "areaId":$("#areaId").val(),  
  27.           "serviceType":$("#serviceType").val(),  
  28.           "serviceGroup":$("#serviceGroup").val(),  
  29.           "areaCode":$("#areaCode").val(),  
  30.           "gprsNode":$("#gprsNode").val(),  
  31.           "distritNum":$("#distritNum").val(),  
  32.           "protocolType":$("#protocolType").val()  
  33.         };  
  34.         if(table1!=null || table1 !=undefined){  
  35.           //        dataTable初始化之后不能再设值,需要销毁重新定义,(数据量大时不适用)  
  36. //            table1.destroy();  
  37. //            bigDataTable(queryData);  
  38.   
  39. //              var src={  
  40. //                url:"getJson_BigData_queryDataByParams",  
  41. //                dataSrc :"dataList",      //自定义数据源,默认为data  
  42. //                type:"post",  
  43. //                data:{"test":$("#protocolType").val()}  
  44. //              };  
  45.   
  46. //            table1.fnSettings().ajax=src; //ajax访问数据  
  47. //            table1.fnPageChange(0,true);  //分页的页数从0开始  
  48.           table1.settings()[0].ajax.data=queryData;  
  49.           table1.ajax.reload();  
  50.         }else{  
  51.           bigDataTable(queryData);  
  52.         }  
  53.   
  54.       });  


上面是前台分页,如果要做后台分业,当然最好就是用后台分页:

1.修改datatable初始化属性,新增

[javascript] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. "serverSide":true,    //true代表后台处理分页,false代表前台处理分页  

2.后台即可获取到每页数据,当前页参数

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. private int length;  
  2.   
  3. private int start:  
  4.       
  5. public int getLength(){  
  6.     return length;  
  7. }  
  8.   
  9. public void setLength(int length){  
  10.     this.length = length;  
  11. }  
  12.   
  13. public int getStart(){  
  14.     return start;  
  15. }  
  16.   
  17. public void setStart(int start){  
  18.     this.start = start;  
  19. }  

我的后台是用struts2写的,其他的也可以用request里面获取,这个值初始化设置之后会一起返回给后端的,然后后端操作数据库的时候,就可以根据这两个参数就行真分页了。


[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public String dataPaging(){  
  2.         resultJson = new HashMap<String,Object>();  
  3.         searchItem = getRequest().getParameter("extra_search");  
  4.         List<Log> list = new ArrayList<Log>();  
  5.         list = logService.queryForPaging(start,length,searchItem);  
  6.         int count = logService.queryForPagingSize(searchItem);  
  7.         resultJson.put("draw", Integer.toString(draw));  
  8.         resultJson.put("recordsTotal", Integer.toString(count));  
  9.         resultJson.put("recordsFiltered",  Integer.toString(count));  
  10.         resultJson.put("data", list);  
  11.         return "success";  
  12.     }  

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public List<T> queryForPaging(int start,int length,String query) {  
  2.         Criteria cri = getSession().createCriteria(this.persistentClass);  
  3.         cri.addOrder(Order.desc("id")).setFirstResult(start).setMaxResults(length);  
  4.         if(query != null && !"".equals(query)){  
  5.             cri.add(Restrictions.like("username", query, MatchMode.ANYWHERE));  
  6.         }  
  7.         List<T> list = cri.list();  
  8.         return list;  
  9.     }  


前后台数据交互:

前台格式:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <table id="activityList" class="table table-bordered table-hover">  
  2.                <thead>  
  3.                <tr>  
  4.                    <th width="10%">ID</th>  
  5.                    <th width="15%">店铺名称</th>  
  6.                    <th width="15%">优惠活动</th>  
  7.                    <th width="15%">开始时间</th>  
  8.                    <th width="15%">结束时间</th>  
  9.                    <th width="15%">操作</th>  
  10.                </tr>  
  11.                </thead>  
  12.                <tbody>  
  13.   
  14.                </tbody>  
  15.            </table>  

[java] view plain copy
在CODE上查看代码片派生到我的代码片
  1. columns:[  
  2.                        { data: 'id' },  
  3.                        { data: 'storeInfo.realName'},  
  4.                        { data: 'content' },  
  5.                        { data: 'startTime',  
  6.                          "render": function ( data, type, full, meta ) {  
  7.                                var dataStr = Date.parse(data);  
  8.                                return new Date(dataStr).Format("yyyy-MM-dd hh:mm:ss");  
  9.                            }  
  10.                        },  
  11.                        { data: 'endTime',  
  12.                            "render": function ( data, type, full, meta ) {  
  13.                                var dataStr = Date.parse(data);  
  14.                                return new Date(dataStr).Format("yyyy-MM-dd hh:mm:ss");  
  15.                            }  
  16.                        },  
  17.                        {data:'id',  
  18.                            "render": function ( data, type, full, meta ) {  
  19.                                var edithtml ="<button class=\"btn btn-info\" type=\"button\" onclick='editorActivity()'>编辑</button> "+  
  20.                                "<button class=\"btn btn-info\" type=\"button\" onclick='deleteActivity()'>删除</button>"  
  21.                                return edithtml;  
  22.                            }  
  23.                        }  
  24.                    ],  
日期格式化:
[javascript] view plain copy
在CODE上查看代码片派生到我的代码片
  1. Date.prototype.Format = function (fmt) { //author: meizz  
  2.                var o = {  
  3.                    "M+"this.getMonth() + 1, //月份  
  4.                    "d+"this.getDate(), //日  
  5.                    "h+"this.getHours(), //小时  
  6.                    "m+"this.getMinutes(), //分  
  7.                    "s+"this.getSeconds(), //秒  
  8.                    "q+": Math.floor((this.getMonth() + 3) / 3), //季度  
  9.                    "S"this.getMilliseconds() //毫秒  
  10.                };  
  11.                if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));  
  12.                for (var k in o)  
  13.                    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));  
  14.                return fmt;  
  15.            }  
后台返回的json数据:
[javascript] view plain copy
在CODE上查看代码片派生到我的代码片
  1. {  
  2.     "resultList": [  
  3.         {  
  4.             "content""元旦大促销活动",  
  5.             "endTime""2016-01-03T22:00:00",  
  6.             "id": 1,  
  7.             "startTime": "2016-01-01T08  
  8. :00:00",  
  9.             "storeInfo": {  
  10.                 "buildingId": 3,  
  11.                 "buildingName""一号楼",  
  12.                 "floorId": 4,  
  13.                 "floorName""一层",  
  14.                 "id": 1,  
  15.                 "realName""KFC",  
  16.                 "siteId": 2,  
  17.                 "siteName""河西万达",  
  18.                 "storeId": 7,  
  19.                 "storeName""Z1",  
  20.                 "zoneId": 1,  
  21.                 "zoneName""万达企业"  
  22.             }  
  23.         },  
  24.         {  
  25.             "content""手撕汉堡,新品上市,买一送一",  
  26.             "endTime""2015-12-30T14:43:38",  
  27.             "id": 2,  
  28.             "startTime""2015-12-29T14:43:34",  
  29.             "storeInfo": {  
  30.                 "buildingId": 3,  
  31.                 "buildingName""一号楼",  
  32.                 "floorId": 4,  
  33.                 "floorName""一层",  
  34.                 "id": 1,  
  35.                 "realName""KFC",  
  36.                 "siteId": 2,  
  37.                 "siteName""河西万达",  
  38.                 "storeId": 7,  
  39.                 "storeName""Z1",  
  40.                 "zoneId": 1,  
  41.                 "zoneName""万达企业"  
  42.             }  
  43.         },  
  44.         {  
  45.             "content": "麻麻黑,免费吃,只  
  46. 要你能吃得完,随便吃",  
  47.             "endTime""2016-02-15T14:45:05",  
  48.             "id": 3,  
  49.             "startTime""2016-02-01T14:44:53",  
  50.             "storeInfo": {  
  51.                 "buildingId": 3,  
  52.                 "buildingName""一号楼",  
  53.                 "floorId": 4,  
  54.                 "floorName""一层",  
  55.                 "id": 1,  
  56.                 "realName""KFC",  
  57.                 "siteId": 2,  
  58.                 "siteName": "  
  59. 河西万达",  
  60.                 "storeId": 7,  
  61.                 "storeName""Z1",  
  62.                 "zoneId": 1,  
  63.                 "zoneName""万达企业"  
  64.             }  
  65.         }  
  66.     ]  
  67. }  

这种方式仅仅是一种方式另外的方式还有个人博客

Bootstrap table 分页,排序,搜索 记录


0 0