本文主要是介绍datatable分页指南--前台分页和后台分页,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、介绍
Datatables是一款jquery表格插件。它是一个高度灵活的工具,可以将任何HTML表格添加高级的交互功能。
- 分页,即时搜索和排序
- 几乎支持任何数据源:DOM, javascript, Ajax 和 服务器处理
- 支持不同主题 DataTables, jQuery UI, Bootstrap, Foundation
- 各式各样的扩展: Editor, TableTools, FixedColumns ……
- 丰富多样的option和强大的API
- 支持国际化
- 超过2900+个单元测试
<link rel="stylesheet" type="text/css" href="/DataTables-1.10.7/css/jquery.dataTables.css"><!-- jQuery -->
<script type="text/javascript" charset="utf8" src="/DataTables-1.10.0/js/jquery.js"></script><!-- DataTables -->
<script type="text/javascript" charset="utf8" src="/DataTables-1.10.7/js/jquery.dataTables.js"></script>
三、html
<table class="table table-bordered table-hover" id="bigDataList"><thead><tr><th>用户id</th><th>主叫</th><th>识别码</th><th>区域id</th><th>服务类型</th><th>服务组</th><th>位置区码</th><th>GPRS节点</th><th>分配记数</th><th>协议类型</th><th>开始时间</th><th>结束时间</th></tr></thead><tbody></tbody></table>
四、js代码
var table1;//dataTable初始化对象function bigDataTable(queryData){table1= $('#bigDataList').DataTable({"paging": true,"lengthChange": true,"searching": true,"ordering": true,"aaSorting" : [[0, "asc"]], //默认的排序方式,第1列,升序排列"info": true,"autoWidth": false,"destroy":true,"processing":true,"scrollX": true, //水平新增滚动轴
// "serverSide":true, //true代表后台处理分页,false代表前台处理分页"aLengthMenu":[10,15,20],"PaginationType" : "full_numbers", //详细分页组,可以支持直接跳转到某页//当处理大数据时,延迟渲染数据,有效提高Datatables处理能力"deferRender": true,"ajax":{url:"getJson_BigData_queryDataByParams",dataSrc:function(data){if(data.callbackCount==null){data.callbackCount=0;}//抛出异常if(data.sqlException){alert(data.sqlException);}//查询结束取消按钮不可用$("#queryDataByParams").removeAttr("disabled");return data.dataList; //自定义数据源,默认为data}, //dataSrc相当于success,在datatable里面不能用success方法,会覆盖datatable内部回调方法type:"post",data:queryData},columns:[{ data: 'user_ip' },{ data: 'calling'},{ data: 'imei' },{ data: 'cell_id'},{ data: 'service_type' },{ data: 'service_group'},{ data: 'lac' },{ data: 'sgsn'},{ data: 'assignment_count' },{ data: 'proto_type'},{ data: 'start_time' },{ data: 'end_time'},],/*是否开启主题*/"bJQueryUI": true,"oLanguage": { // 语言设置"sLengthMenu": "每页显示 _MENU_ 条记录","sZeroRecords": "抱歉, 没有找到","sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据","sInfoEmpty": "没有数据","sInfoFiltered": "(从 _MAX_ 条数据中检索)","sZeroRecords": "没有检索到数据","sSearch": "检索:","oPaginate": {"sFirst": "首页","sPrevious": "前一页","sNext": "后一页","sLast": "尾页"}},});}
点击请求ajax,返回渲染数据:
//点击查询$("#queryDataByParams").on("click",function() {var reg = new RegExp("^[0-9]*$");var startTime=$("#searchDateRange").val().substring(0,19).replace(/-/g, '/');var endTime=$("#searchDateRange").val().substring(22,41).replace(/-/g, '/');var date1=new Date(startTime); //开始时间var date2=new Date(endTime); //结束时间var date3=date2.getTime()-date1.getTime() //时间差的毫秒数if(date3>60*60*24*1000){alert("开始时间与结束时间间隔大于24小时!");return false;}if(!$("#searchDateRange").val() || $("#searchDateRange").val()=="填写时间段"){alert("时间区段不能为空!");return false;}if(!$("#calling").val() && !reg.test($("#calling").val())){alert("请输入全数字!");}//查询时候设置按钮不可用$("#queryDataByParams").attr("disabled", true);var queryData={"startseg":$("#searchDateRange").val(),"callseg":$("#calling").val(),"identifiCode":$("#identifiCode").val(),"areaId":$("#areaId").val(),"serviceType":$("#serviceType").val(),"serviceGroup":$("#serviceGroup").val(),"areaCode":$("#areaCode").val(),"gprsNode":$("#gprsNode").val(),"distritNum":$("#distritNum").val(),"protocolType":$("#protocolType").val()};if(table1!=null || table1 !=undefined){// dataTable初始化之后不能再设值,需要销毁重新定义,(数据量大时不适用)
// table1.destroy();
// bigDataTable(queryData);// var src={
// url:"getJson_BigData_queryDataByParams",
// dataSrc :"dataList", //自定义数据源,默认为data
// type:"post",
// data:{"test":$("#protocolType").val()}
// };// table1.fnSettings().ajax=src; //ajax访问数据
// table1.fnPageChange(0,true); //分页的页数从0开始table1.settings()[0].ajax.data=queryData;table1.ajax.reload();}else{bigDataTable(queryData);}});
上面是前台分页,如果要做后台分业,当然最好就是用后台分页:
1.修改datatable初始化属性,新增
"serverSide":true, //true代表后台处理分页,false代表前台处理分页
2.后台即可获取到每页数据,当前页参数
private int length;private int start:public int getLength(){return length;}public void setLength(int length){this.length = length;}public int getStart(){return start;}public void setStart(int start){this.start = start;}
我的后台是用struts2写的,其他的也可以用request里面获取,这个值初始化设置之后会一起返回给后端的,然后后端操作数据库的时候,就可以根据这两个参数就行真分页了。
public String dataPaging(){resultJson = new HashMap<String,Object>();searchItem = getRequest().getParameter("extra_search");List<Log> list = new ArrayList<Log>();list = logService.queryForPaging(start,length,searchItem);int count = logService.queryForPagingSize(searchItem);resultJson.put("draw", Integer.toString(draw));resultJson.put("recordsTotal", Integer.toString(count));resultJson.put("recordsFiltered", Integer.toString(count));resultJson.put("data", list);return "success";}
public List<T> queryForPaging(int start,int length,String query) {Criteria cri = getSession().createCriteria(this.persistentClass);cri.addOrder(Order.desc("id")).setFirstResult(start).setMaxResults(length);if(query != null && !"".equals(query)){cri.add(Restrictions.like("username", query, MatchMode.ANYWHERE));}List<T> list = cri.list();return list;}
前后台数据交互:
前台格式:
<table id="activityList" class="table table-bordered table-hover"><thead><tr><th width="10%">ID</th><th width="15%">店铺名称</th><th width="15%">优惠活动</th><th width="15%">开始时间</th><th width="15%">结束时间</th><th width="15%">操作</th></tr></thead><tbody></tbody></table>
columns:[{ data: 'id' },{ data: 'storeInfo.realName'},{ data: 'content' },{ data: 'startTime',"render": function ( data, type, full, meta ) {var dataStr = Date.parse(data);return new Date(dataStr).Format("yyyy-MM-dd hh:mm:ss");}},{ data: 'endTime',"render": function ( data, type, full, meta ) {var dataStr = Date.parse(data);return new Date(dataStr).Format("yyyy-MM-dd hh:mm:ss");}},{data:'id',"render": function ( data, type, full, meta ) {var edithtml ="<button class=\"btn btn-info\" type=\"button\" οnclick='editorActivity()'>编辑</button> "+"<button class=\"btn btn-info\" type=\"button\" οnclick='deleteActivity()'>删除</button>"return edithtml;}}],
日期格式化:Date.prototype.Format = function (fmt) { //author: meizzvar o = {"M+": this.getMonth() + 1, //月份"d+": this.getDate(), //日"h+": this.getHours(), //小时"m+": this.getMinutes(), //分"s+": this.getSeconds(), //秒"q+": Math.floor((this.getMonth() + 3) / 3), //季度"S": this.getMilliseconds() //毫秒};if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));for (var k in o)if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));return fmt;}
后台返回的json数据:{"resultList": [{"content": "元旦大促销活动","endTime": "2016-01-03T22:00:00","id": 1,"startTime": "2016-01-01T08 :00:00","storeInfo": {"buildingId": 3,"buildingName": "一号楼","floorId": 4,"floorName": "一层","id": 1,"realName": "KFC","siteId": 2,"siteName": "河西万达","storeId": 7,"storeName": "Z1","zoneId": 1,"zoneName": "万达企业"}},{"content": "手撕汉堡,新品上市,买一送一","endTime": "2015-12-30T14:43:38","id": 2,"startTime": "2015-12-29T14:43:34","storeInfo": {"buildingId": 3,"buildingName": "一号楼","floorId": 4,"floorName": "一层","id": 1,"realName": "KFC","siteId": 2,"siteName": "河西万达","storeId": 7,"storeName": "Z1","zoneId": 1,"zoneName": "万达企业"}},{"content": "麻麻黑,免费吃,只 要你能吃得完,随便吃","endTime": "2016-02-15T14:45:05","id": 3,"startTime": "2016-02-01T14:44:53","storeInfo": {"buildingId": 3,"buildingName": "一号楼","floorId": 4,"floorName": "一层","id": 1,"realName": "KFC","siteId": 2,"siteName": " 河西万达","storeId": 7,"storeName": "Z1","zoneId": 1,"zoneName": "万达企业"}}] }
中文文档:点击打开链接
这篇关于datatable分页指南--前台分页和后台分页的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!