datatables的使用


     在開發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();  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM