datatables的使用

简介: 在开发web项目中,界面就是一个以丰富友好的样式来展现数据的窗口,同样的数据不用的展现形式给人不同的体验,数据列表是数据是一种常见展现形式,对于数据列表的一个最基本的要求就是能够实现分页以及检索功能。

     在开发web项目中,界面就是一个以丰富友好的样式来展现数据的窗口,同样的数据不用的展现形式给人不同的体验,数据列表是数据是一种常见展现形式,对于数据列表的一个最基本的要求就是能够实现分页以及检索功能。

        datatables是一个不错的基于jQuery的前端框架,它除了满足我们基本的分页和检索要求还有其他高级的功能。如果对datatables的高级功能感兴趣可以查看官网的API了解具体如何使用。

        下面是一些datatables的常用的初始化配置。

         页面HTML代码如下

 

[html]  view plain  copy
 
  1. <table width="100%" class="display" id="dataGrid" cellspacing="0">  
  2.     <thead>  
  3.     <tr>  
  4.         <th>主键</th><th>序号</th><th>接口名称</th><th>问题类型</th><th>问题内容</th><th>咨询时间</th><th>联系人</th><th>处理状态</th><th>完成日期</th><th>问题细节</th><th>批次号</th><th>操作</th>  
  5.     </tr>  
  6.     </thead>  
  7. </table>  

 

 

       在正式使用datatables的脚本之前我们需要做一些准备工作引入脚本文件等参考如下下面的文件中并没有提到jquery和datatables脚本文件。这个两个脚本文件 handlerbars是一个js模板引擎框架,fnReloadAjax是datatables的一个plugin插件。我们使用到了这两个js脚本。

 

[javascript]  view plain  copy
 
  1. <script src="${ctp}/js/handlebars-v4.0.5.js"></script>  
  2. <script src="${ctp}/js/fnReloadAjax.js"></script>  
  3. <script id="tpl" type="text/x-handlebars-template">  
  4.     {{#each func}}  
  5.         <button type="button" class="btn{{this.type}}" onclick="{{this.fn}}">{{this.name}}</button>  
  6.     {{/each}}  
  7. </script>  


       下面是datatables核心的js脚本内容

 

 

[javascript]  view plain  copy
 
  1. function initDataGrid(){  
  2.       
  3.        var tpl = $("#tpl").html();  
  4.        //预编译模板  
  5.        var template = Handlebars.compile(tpl);  
  6.     /**************初始化数据表格****************************/  
  7.     dataTable = $("#dataGrid").dataTable({  
  8.         "language": {  
  9.             "url": "${ctp}/jqueryplugin/datatables/js/Chinese.json"  
  10.         },  
  11.         //processing: true,  
  12.         
  13.         serverSide: true,  
  14.         ajax: {  
  15.             url: '${ctp}/rest/dock/listDockQuestion',  
  16.             type: 'POST'  
  17.         },  
  18.         /**  
  19.         id,moId,createTime,processDate,questionType, 
  20.         questionContent,accessChannel,contactId,processResult,processDescription 
  21.         interfaceId,questionDetail,batchId,contactName,sequence 
  22.         */  
  23.         "columns": [  
  24.                 { "data": "id","targets": -1,"visible": false  },  
  25.                 { "data": "sequence","targets": 0 },  
  26.                 { "data": "interfaceId","targets": 1 },  
  27.                 { "data": "questionType" ,"targets": 2},  
  28.                 { "data": "questionContent","targets": 3 },  
  29.                 { "data": "processDate" ,"targets": 4},  
  30.                 { "data": "contactName" ,"targets": 5},  
  31.                 { "data": "processResult" ,"targets": 6} ,  
  32.                 { "data": "processDate" ,"targets": 7},  
  33.                 { "data": "questionDetail" ,"targets": 8},  
  34.                 { "data": "batchId" ,"targets": 9,"visible": false }  
  35.                      
  36.                       
  37.          ],  
  38.         //自定义功列  
  39.     "columnDefs": [  
  40.                     {  
  41.                        "render": function ( data, type, row ) {  
  42.                           
  43.                             return $("#interfaceId_"+data).val();  
  44.                           
  45.                         },  
  46.                         "targets": 2  
  47.                     },  
  48.                     {  
  49.                        "render": function ( data, type, row ) {  
  50.                           
  51.                             return $("#questionType_"+data).val();  
  52.                         },  
  53.                         "targets": 3  
  54.                      },  
  55.                      {  
  56.                            "render": function ( data, type, row ) {  
  57.                               
  58.                                 return $("#processResult_"+data).val();  
  59.                             },  
  60.                             "targets": 7  
  61.                      },  
  62.                    {  
  63.                        "render": function ( data, type, row ) {  
  64.                           
  65.                             var questionType=row['questionType'];  
  66.                             return $("#TEC_PROBLEM_"+questionType+"_DETAIL_"+data).val();  
  67.                         },  
  68.                         "targets": 4  
  69.                      },  
  70.                     {  
  71.                         "render": function ( data, type, row ) {  
  72.                             var status=row['processResult'];                          
  73.                             var context =null;  
  74.                             if("99"==status){  
  75.                                 context =  
  76.                                 {  
  77.                                      func:[  
  78.                                           {"name": "详", "fn": "viewDockQuestion('"+row['id']+"')", "type": "5"}  
  79.                                      ]  
  80.                                  };  
  81.                             }else{  
  82.                                 context =  
  83.                                 {  
  84.                                      func:[  
  85.                                           {"name": "办", "fn": "updateDockQuestion('"+row['id']+"')", "type": "5"}  
  86.                                      ]  
  87.                                  };  
  88.                             }  
  89.                             var html = template(context);  
  90.                             return html;  
  91.                          },  
  92.                          "targets": 11  
  93.                     }  
  94.                       
  95.         ],  
  96.         //创建行回调函数  创建行之后  
  97.     "createdRow": function ( row, data, index ) {  
  98.             tmpData.push(data);  
  99.         }  
  100.          
  101.     });  
  102.       
  103.     dataGrid=dataTable;  
  104.       
  105. }  

 

        columnDefs属性render 用来自定义表格显示的数据,通常我们有些反显数据时会用到,以及我们自定义一些操作写一下function时会使用到 target 用来指向表格的哪一列。 createdRow   事件是指创建完一行之后触发的事件,通过这一事件我们可以做些我们需要的工作。

       接下来就是如何解决服务端如何分页的问题,下面是一段Java代码供大家进行参考,在代码之后我会进行一个简单描述

 

[java]  view plain  copy
 
  1. @POST  
  2.   @Path("listDockQuestion")  
  3.   @Produces(MediaType.APPLICATION_JSON)  
  4.   public Object getDockQuestionList(@FormParam(value = "start") long start, @FormParam(value = "length") long length,  
  5.       @FormParam(value = "draw") String draw) {  
  6.     /** 
  7.      * { "draw": 1, "recordsTotal": 57, "recordsFiltered": 57, "data": [ { }]} 
  8.      */  
  9.     // 获取Datatables发送的参数 必要  
  10.     // 定义查询数据总记录数  
  11.     // 条件过滤后记录数 必要recordsFiltered  
  12.     // 表的总记录数 必要 recordsTotal  
  13.     Map<String, Object> paramMap = new HashMap<String, Object>();  
  14.     paramMap.put("start", start);  
  15.     paramMap.put("length", length);  
  16.     paramMap.put("end", start + length);  
  17.     Map<String, Object> respMap = new HashMap<String, Object>();  
  18.     // respMap.put("draw", "1");  
  19.     Long sum = dockService.countDockQuestion(paramMap);  
  20.     respMap.put("recordsTotal", sum);  
  21.     respMap.put("recordsFiltered", sum);  
  22.     respMap.put("data", dockService.listDockQuestion(paramMap));  
  23.     return respMap;  
  24.   }  


        { "draw": 1, "recordsTotal": 57, "recordsFiltered": 57, "data": [ { }]} 是要返回的json数据格式,datatables向服务端传的参数中两个重要参数是我们分页使用到的,(start +1) 是从数据库中的哪一行开始取值,如果要去第11行的数据开始取值,start会传入10,而length是指要取多少行数据,这对于mysql数据的分页写sql非常方便只需要在自己SELECT语句之后加上 LIMIT  start, length  。draw是请求的序号,start是数据的偏移量,length是需要返回的最大数据条数

 

        下面一段代码是表格异步刷新的插件fnReloadAjax代码

 

[javascript]  view plain  copy
 
  1. /** 
  2.  * By default DataTables only uses the sAjaxSource variable at initialisation 
  3.  * time, however it can be useful to re-read an Ajax source and have the table 
  4.  * update. Typically you would need to use the `fnClearTable()` and 
  5.  * `fnAddData()` functions, however this wraps it all up in a single function 
  6.  * call. 
  7.  * 
  8.  * DataTables 1.10 provides the `dt-api ajax.url()` and `dt-api ajax.reload()` 
  9.  * methods, built-in, to give the same functionality as this plug-in. As such 
  10.  * this method is marked deprecated, but is available for use with legacy 
  11.  * version of DataTables. Please use the new API if you are used DataTables 1.10 
  12.  * or newer. 
  13.  * 
  14.  *  @name fnReloadAjax 
  15.  *  @summary Reload the table's data from the Ajax source 
  16.  *  @author [Allan Jardine](http://sprymedia.co.uk) 
  17.  *  @deprecated 
  18.  * 
  19.  *  @param {string} [sNewSource] URL to get the data from. If not give, the 
  20.  *    previously used URL is used. 
  21.  *  @param {function} [fnCallback] Callback that is executed when the table has 
  22.  *    redrawn with the new data 
  23.  *  @param {boolean} [bStandingRedraw=false] Standing redraw (don't changing the 
  24.  *      paging) 
  25.  * 
  26.  *  @example 
  27.  *    var table = $('#example').dataTable(); 
  28.  *     
  29.  *    // Example call to load a new file 
  30.  *    table.fnReloadAjax( 'media/examples_support/json_source2.txt' ); 
  31.  * 
  32.  *    // Example call to reload from original file 
  33.  *    table.fnReloadAjax(); 
  34.  */  
  35.   
  36. jQuery.fn.dataTableExt.oApi.fnReloadAjax = function ( oSettings, sNewSource, fnCallback, bStandingRedraw )  
  37. {  
  38.     // DataTables 1.10 compatibility - if 1.10 then `versionCheck` exists.  
  39.     // 1.10's API has ajax reloading built in, so we use those abilities  
  40.     // directly.  
  41.     if ( jQuery.fn.dataTable.versionCheck ) {  
  42.         var api = new jQuery.fn.dataTable.Api( oSettings );  
  43.   
  44.         if ( sNewSource ) {  
  45.             api.ajax.url( sNewSource ).load( fnCallback, !bStandingRedraw );  
  46.         }  
  47.         else {  
  48.             api.ajax.reload( fnCallback, !bStandingRedraw );  
  49.         }  
  50.         return;  
  51.     }  
  52.   
  53.     if ( sNewSource !== undefined && sNewSource !== null ) {  
  54.         oSettings.sAjaxSource = sNewSource;  
  55.     }  
  56.   
  57.     // Server-side processing should just call fnDraw  
  58.     if ( oSettings.oFeatures.bServerSide ) {  
  59.         this.fnDraw();  
  60.         return;  
  61.     }  
  62.   
  63.     this.oApi._fnProcessingDisplay( oSettings, true );  
  64.     var that = this;  
  65.     var iStart = oSettings._iDisplayStart;  
  66.     var aData = [];  
  67.   
  68.     this.oApi._fnServerParams( oSettings, aData );  
  69.   
  70.     oSettings.fnServerData.call( oSettings.oInstance, oSettings.sAjaxSource, aData, function(json) {  
  71.         /* Clear the old information from the table */  
  72.         that.oApi._fnClearTable( oSettings );  
  73.   
  74.         /* Got the data - add it to the table */  
  75.         var aData =  (oSettings.sAjaxDataProp !== "") ?  
  76.             that.oApi._fnGetObjectDataFn( oSettings.sAjaxDataProp )( json ) : json;  
  77.   
  78.         for ( var i=0 ; i<aData.length ; i++ )  
  79.         {  
  80.             that.oApi._fnAddData( oSettings, aData[i] );  
  81.         }  
  82.   
  83.         oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();  
  84.   
  85.         that.fnDraw();  
  86.   
  87.         if ( bStandingRedraw === true )  
  88.         {  
  89.             oSettings._iDisplayStart = iStart;  
  90.             that.oApi._fnCalculateEnd( oSettings );  
  91.             that.fnDraw( false );  
  92.         }  
  93.   
  94.         that.oApi._fnProcessingDisplay( oSettings, false );  
  95.   
  96.         /* Callback user function - for event handlers etc */  
  97.         if ( typeof fnCallback == 'function' && fnCallback !== null )  
  98.         {  
  99.             fnCallback( oSettings );  
  100.         }  
  101.     }, oSettings );  
  102. };  

 

 

        下面的脚本是如何调用该插件来实现datatables异步刷新

 

[javascript]  view plain  copy
 
    1. dataGrid.fnReloadAjax();  
目录
相关文章
|
7月前
|
JavaScript 索引
jQuery 隔行变色
jQuery 隔行变色
29 0
|
7月前
|
JavaScript
jQuery addClass()、removeClass()、hasClass()
jQuery addClass()、removeClass()、hasClass()
40 0
|
存储 JavaScript 前端开发
JQuery jquerysessionjs插件使用介绍
JQuery jquerysessionjs插件使用介绍
66 0
|
JavaScript 前端开发
3、DataTables
3、DataTables
65 0
|
XML JavaScript 前端开发
jqGrid 详解大全
jqGrid 各种参数 详解 JQGrid JQGrid是一个在jquery基础上做的一个表格控件,以ajax的方式和服务器端通信。 JQGrid Demo 是一个在线的演示项目。
3475 0
|
JSON 数据格式 Java