项目中DataTables分页插件的使用
在项目开发的过程中,一般都会对表格进行分页处理,大多是情况下会在项目中配置好后台分页插件,提高效率,减轻浏览器的压力。但是有时会遇到有些数据不能直接通过分页插件操作数据库进行分页数据查询,那就需要用到前端分页。DataTables分页插件就很好用,后台通过将查询好的数据封装成具体格式的数据(json),传到前台,前台通过配置DataTables插件的配置选项,对数据进行分页显示。下面为DataTables插件的使用过程:
1.引入头文件
// 引入DataTables样式文件 <link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" /> // 引入JQuery <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script> // 引入js文件 <script type="text/javascript" charset="utf8" src="http://cdn.datatables.net/1.10.16/js/jquery.dataTables.js"></script>
2.前端表格html
<table class="m-table m-table-rds" id="example2" style="text-align: center;"> <thead> <tr> <th style="text-align: center;">日期</th> <th style="text-align: center;">IP总数</th> <th style="width: 80px; text-align: center;">访问次数</th> </tr> </thead> </table>
3.前端配置DataTables插件
<script> $(function(){ var beginDate = $('#beginDate').val(); var endDate = $('#endDate').val(); $('#example2').DataTable( { "serverSide": true, "aLengthMenu":[7, 15, 30], 'iDisplayLength': 7, 'order' : [0,'desc'], searching: false, lengthChange: true, paging: true, pagingType:'full_numbers', scrollCollapse: true, serverSide: false, search: true, processing: true, /* scrollY: 500, 表格的高度限制*/ scrollX: "99.9%", scrollXInner: "99.9%", scrollCollapse: true, jQueryUI: false, autoWidth: true, autoSearch: false, language: { "sProcessing": "处理中...", "sLengthMenu": "显示 _MENU_ 项搜索结果", "sZeroRecords": "没有匹配结果", "sInfo": "显示第 _START_ 至 _END_ 项结果,共 _TOTAL_ 条记录", "sInfoEmpty": "显示第 0 至 0 项结果,共 0 项", "sInfoFiltered": "(由 _MAX_ 项结果过滤)", "sInfoPostFix": "", "sSearch": "搜索:", "sUrl": "", "sEmptyTable": "未搜索到数据", "sLoadingRecords": "载入中...", "sInfoThousands": ",", "oPaginate": { "sFirst": "首页", "sPrevious": "上页", "sNext": "下页", "sLast": "末页" }, "oAria": { "sSortAscending": ": 以升序排列此列", "sSortDescending": ": 以降序排列此列" } }, ajax: { url: "${_b}/jcnw/main/getData", data:{beginDate:beginDate,endDate:endDate}, dataSrc:'data', type:'post', error: function(data) { console.log(data); } }, "columns": [ { "data": "date" }, { "data": "ip_num" }, { "data": "fw_num" } ] } ); }) </script>
4.后台controller
@RequestMapping(value="/*/getData",method= {RequestMethod.GET,RequestMethod.POST}) public void getData( @RequestParam(value = "beginDate", required = true) String beginDate, @RequestParam(value = "endDate", required = true) String endDate, HttpServletRequest request,HttpServletResponse response) throws SQLException, ParseException, IOException{ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); int days = differentDaysByMillisecond(sdf.parse(endDate), sdf.parse(beginDate)); String date = beginDate; List<Map<String, Object>> counts = new ArrayList<>(); for (int i = 0; i <= days; i++) { Map<String, Object> count = fwtjService.getCount(date); count.put("date", date); date = getPastDate(date,-1); counts.add(count); } JSONObject json = new JSONObject(); json.put("data",counts); response.getWriter().write(json.toString()); }