DataTables—服务器端翻页

本文是jquery<--json-->spring(3.0)系列的第三篇。


jquery与yui相比,感觉写法很简洁,但也有个问题是配套的jquery ui中的页面控件 
不是很全,很多要借助plugin,而这些plugin良莠不齐,选用时要自己好好挑一挑。 
列表是一个常用的页面控件,我选了半天发现DataTables这款用的人比较多,就试了 
试服务器端翻页功能,现总结如下。 

DataTables的主页是http://www.datatables.net/ 

先上个这个demo的截图,设想的操作是输入客户名称,按检索后进行模糊检索进行分 
页显示,每页显示8条记录。 




1 页面部分 
使用DataTables时,html需要如下书写,其中tfoot部分是表表格的下部标题,可以不 
要。

Html代码 

  1. <table class="display" id="customerInfo">  
  2.     <thead>  
  3.         <tr>  
  4.             <th>ID</th>  
  5.             略   
  6.             <th>身高</th>  
  7.         </tr>  
  8.     </thead>  
  9.     <tbody>  
  10.         <tr>  
  11.             <td colspan="8"></td>    
  12.         </tr>  
  13.     </tbody>  
  14.     <tfoot>  
  15.         <tr>  
  16.             <th>ID</th>  
  17.             略   
  18.             <th>身高</th>  
  19.         </tr>  
  20.     </tfoot>  
  21. </table>  



js部分这样写:

Javascript代码 

  1. $('#customerInfo').dataTable();  



对于从服务器端取数据,还要指定几个参数: 
bServerSide:true 
sAjaxSource:获取数据的url 

这样,在DataTables需要数据时会调用jquery的getJSON获取数据,其中url就是sAjaxSource, 
同时传递一堆自定义的参数,包括需要显示的起始记录数,需要显示的记录数,列数,排序 
列等等,具体可以参看这里http://www.datatables.net/usage/server-side。其中一个比较 
特殊的是sEcho,这个参数需要以后原封不动地返回给页面。 
由于默认是以$.getJSON发送请求,所以http命令是GET,参数是以url参数的方式传递的,我 
希望以POST命令,以json方式发送请求,而且要加上客户名称这个参数,所以这里需要做些修 
改。 
DataTables通过fnServerData提供了这样一个接口,fnServerData是与服务器端交换数据时被 
调用的函数,默认实现是如上所说的通过getJSON发送请求,然后接收特定格式的json数据(这 
个在服务器端处理部分再说)。fnServerData会接到3个参数: 
sSource: 接收数据的url,就是sAjaxSource中指定的地址 
aoData:DataTables定义的参数,是一个数组,其中每个元素是一个name-value对,我需要 
        把客户名称这个参数加进去 
fnCallback:服务器返回数据后的处理函数,我需要按DataTables期望的格式传入返回数据 
最后自定义的fnServerData如下所示:

Javascript代码 

  1. function retrieveData( sSource, aoData, fnCallback ) {   
  2.     //将客户名称加入参数数组   
  3.     aoData.push( { "name": "customerName", "value": $("#customerName").val() } );   
  4.   
  5.     $.ajax( {   
  6.         "type": "POST",    
  7.         "contentType": "application/json",   
  8.         "url": sSource,    
  9.         "dataType": "json",   
  10.         "data": JSON.stringify(aoData), //以json格式传递   
  11.         "success": function(resp) {   
  12.             fnCallback(resp.returnObject); //服务器端返回的对象的returnObject部分是要求的格式  
  13.         }   
  14.     });   
  15. }  



页面的初始化及查询按钮的处理函数如下所示:

Javascript代码 

  1. var oTable = null;   
  2.   
  3. $(function() {   
  4.     $("#customerInfo").hide();   
  5. } );   
  6.   
  7. //“检索”按钮的处理函数   
  8. function search() {   
  9.     if (oTable == null) { //仅第一次检索时初始化Datatable   
  10.         $("#customerInfo").show();   
  11.         oTable = $('#customerInfo').dataTable( {   
  12.             "bAutoWidth": false,                    //不自动计算列宽度   
  13.             "aoColumns": [                          //设定各列宽度   
  14.                             {"sWidth": "15px"},   
  15.                             {"sWidth": "80px"},   
  16.                             {"sWidth": "160px"},   
  17.                             {"sWidth": "110px"},   
  18.                             {"sWidth": "120px"},   
  19.                             {"sWidth": "140px"},   
  20.                             {"sWidth": "140px"},   
  21.                             {"sWidth": "*"}   
  22.                         ],   
  23.             "bProcessing": true,                    //加载数据时显示正在加载信息   
  24.             "bServerSide": true,                    //指定从服务器端获取数据   
  25.             "bFilter": false,                       //不使用过滤功能   
  26.             "bLengthChange": false,                 //用户不可改变每页显示数量   
  27.             "iDisplayLength": 8,                    //每页显示8条数据   
  28.             "sAjaxSource": "customerInfo/search.do",//获取数据的url   
  29.             "fnServerData": retrieveData,           //获取数据的处理函数   
  30.             "sPaginationType": "full_numbers",      //翻页界面类型   
  31.             "oLanguage": {                          //汉化   
  32.                 "sLengthMenu": "每页显示 _MENU_ 条记录",   
  33.                 "sZeroRecords": "没有检索到数据",   
  34.                 "sInfo": "当前数据为从第 _START_ 到第 _END_ 条数据;总共有 _TOTAL_ 条记录",   
  35.                 "sInfoEmtpy": "没有数据",   
  36.                 "sProcessing": "正在加载数据...",   
  37.                 "oPaginate": {   
  38.                     "sFirst": "首页",   
  39.                     "sPrevious": "前页",   
  40.                     "sNext": "后页",   
  41.                     "sLast": "尾页"  
  42.                 }   
  43.             }   
  44.         });   
  45.     }   
  46.   
  47.     //刷新Datatable,会自动激发retrieveData   
  48.     oTable.fnDraw();   
  49. }  



2 服务器端 
页面请求的参数是一个数组,其中每个元素是一个name-value对,我如下定义

Java代码 

  1. public class JSONParam {   
  2.     private String name;   
  3.     private String value;   
  4.        
  5.     //略   
  6. }  


对应的处理函数如下定义:

Java代码 

  1. @RequestMapping(value = "/search", method = RequestMethod.POST)   
  2. @ResponseBody  
  3. public JSONResponse search(@RequestBody JSONParam[] params){   
  4.     //略   
  5. }  


在这个函数里大致的处理是先取出所需的参数,然后检索数据,最后将DataTables期望的 
格式的数据放入返回对象JSONResponse的returnObject部分。 
DataTables期望的数据格式如下: 

    "sEcho": 页面发来的参数,原样返回, 
    "iTotalRecords": 过滤前总记录数, 
    "iTotalDisplayRecords": 过滤后总记录数,我没有使用过滤,不太清楚和iTotalRecords的区别, 
    "aaData": 包含数据的2维数组 


对应的java定义如下:

Java代码 

  1. public class DataTableReturnObject {   
  2.     private long iTotalRecords;   
  3.     private long iTotalDisplayRecords;   
  4.     private String sEcho;   
  5.     private String[][] aaData;   
  6.        
  7.     public DataTableReturnObject(long totalRecords, long totalDisplayRecords, String echo, String[][] d) {   
  8.         //略   
  9.     }   
  10.        
  11.     //略   
  12. }  



完整的服务器端处理函数如下:

Java代码 

  1. @RequestMapping(value = "/search", method = RequestMethod.POST)   
  2. @ResponseBody  
  3. public JSONResponse search(@RequestBody JSONParam[] params) throws IllegalAccessException, InvocationTargetException    
  4.     //convertToMap定义于父类,将参数数组中的所有元素加入一个HashMap   
  5.     HashMap<String, String> paramMap = convertToMap(params);   
  6.     String sEcho = paramMap.get("sEcho");   
  7.     String customerName = paramMap.get("customerName");   
  8.     int start = Integer.parseInt(paramMap.get("iDisplayStart"));   
  9.     int length = Integer.parseInt(paramMap.get("iDisplayLength"));   
  10.        
  11.     //customerService.search返回的第一个元素是满足查询条件的记录总数,后面的是   
  12.     //页面当前页需要显示的记录数据   
  13.     List<Object> customerList = customerService.search(customerName, start, length);   
  14.     Long count = (Long)customerList.get(0);   
  15.        
  16.     //将查询结果转换为一个二维数组   
  17.     int record = customerList.size() - 1;   
  18.     String[][] data = new String[record][];   
  19.     for(int i=0; i<record; i++) {   
  20.         Customer customer = (Customer)customerList.get(i+1);   
  21.         JSONCustomer jsonCustomer = new JSONCustomer();   
  22.         BeanUtils.copyProperties(jsonCustomer, customer);   
  23.         data[i] = jsonCustomer.toArray();   
  24.     }   
  25.        
  26.     return successed(new DataTableReturnObject(count.longValue(), count.longValue(), sEcho, data));   
  27. }  



数据返回到页面后,如上所述,取出response中的returnObject交给DataTables的函数进行处理 
就可以了 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是datatables的教程: 1. 引入datatables的css和js文件 ```html <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.css"> <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.js"></script> ``` 2. 在html中创建一个表格 ```html <table id="example" class="display" style="width:100%"> <thead> <tr> <th>Name</th> <th>Position</th> <th>Office</th> <th>Age</th> <th>Start date</th> <th>Salary</th> </tr> </thead> <tbody> <tr> <td>Tiger Nixon</td> <td>System Architect</td> <td>Edinburgh</td> <td>61</td> <td>2011/04/25</td> <td>$320,800</td> </tr> <tr> <td>Garrett Winters</td> <td>Accountant</td> <td>Tokyo</td> <td>63</td> <td>2011/07/25</td> <td>$170,750</td> </tr> <tr> <td>Ashton Cox</td> <td>Junior Technical Author</td> <td>San Francisco</td> <td>66</td> <td>2009/01/12</td> <td>$86,000</td> </tr> <tr> <td>Cedric Kelly</td> <td>Senior Javascript Developer</td> <td>Edinburgh</td> <td>22</td> <td>2012/03/29</td> <td>$433,060</td> </tr> <tr> <td>Airi Satou</td> <td>Accountant</td> <td>Tokyo</td> <td>33</td> <td>2008/11/28</td> <td>$162,700</td> </tr> </tbody> </table> ``` 3. 在js中初始化datatables ```javascript $(document).ready(function() { $('#example').DataTable(); } ); ``` 4. datatables还有很多配置选项,例如分页、排序、搜索等,可以在初始化时传入选项进行配置,例如: ```javascript $(document).ready(function() { $('#example').DataTable( { "paging": true, "ordering": true, "info": true } ); } ); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值