DataTables+SpringMVC實(shí)現(xiàn)服務(wù)器端分頁處理

DataTables的主頁是 http://www.datatables.net/,中文主頁http://www.datatables.club/


  1. View層
jsp或者h(yuǎn)tml代碼:
<table id="example" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>First name</th>
                <th>Last name</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>First name</th>
                <th>Last name</th>      
            </tr>
        </tfoot>
    </table>
JS代碼:
$("#example").DataTable({
            "bLengthChange": false,
            "bFilter": false,
            "bSort": false,
            "bInfo": true,
            "bProcessing": true, // 加載條
            "iDisplayLength": 10,
            "columns" : [ {
                "data" : "firstName"
            }, {
                "data" : "lastName"
            }],
            "bProcessing": false, // 是否顯示取數(shù)據(jù)時(shí)的那個(gè)等待提示
            "bServerSide": true,//這個(gè)用來指明是通過服務(wù)端來取數(shù)據(jù)
            "sAjaxSource": "items/list",//這個(gè)是請(qǐng)求的地址,Rest API or JSP的action
            "fnServerData": retrieveData, // 獲取數(shù)據(jù)的處理函數(shù)
            "oLanguage": {

                "sProcessing": "正在加載中......",

                "sLengthMenu": "每頁顯示 _MENU_ 條記錄",

                "sZeroRecords": "對(duì)不起,查詢不到相關(guān)數(shù)據(jù)!",

                "sEmptyTable": "表中無數(shù)據(jù)存在!",

                "sInfo": "當(dāng)前顯示 _START_ 到 _END_ 條,共 _TOTAL_ 條記錄",

                "sInfoFiltered": "數(shù)據(jù)表中共為 _MAX_ 條記錄",

                "oPaginate": {

                    "sFirst": "首頁",

                    "sPrevious": "上一頁",

                    "sNext": "下一頁",

                    "sLast": "末頁"

                }

            }
        });

對(duì)于從服務(wù)器端取數(shù)據(jù),還要指定幾個(gè)參數(shù):
bServerSide:true
sAjaxSource:獲取數(shù)據(jù)的url

這樣,在DataTables需要數(shù)據(jù)時(shí)會(huì)調(diào)用jquery的getJSON獲取數(shù)據(jù),其中url就是sAjaxSource,
同時(shí)傳遞一堆自定義的參數(shù),包括需要顯示的起始記錄數(shù),需要顯示的記錄數(shù),列數(shù),排序
列等等,具體可以參看這里http://www.datatables.net/usage/server-side。其中一個(gè)比較
特殊的是sEcho,這個(gè)參數(shù)需要以后原封不動(dòng)地返回給頁面。
由于默認(rèn)是以$.getJSON發(fā)送請(qǐng)求,所以http命令是GET,參數(shù)是以u(píng)rl參數(shù)的方式傳遞的,我
希望以POST命令,以json方式發(fā)送請(qǐng)求,而且要加上客戶名稱這個(gè)參數(shù),所以這里需要做些修
改。
DataTables通過fnServerData提供了這樣一個(gè)接口,fnServerData是與服務(wù)器端交換數(shù)據(jù)時(shí)被
調(diào)用的函數(shù),默認(rèn)實(shí)現(xiàn)是如上所說的通過getJSON發(fā)送請(qǐng)求,然后接收特定格式的json數(shù)據(jù)(這
個(gè)在服務(wù)器端處理部分再說)。fnServerData會(huì)接到3個(gè)參數(shù):
sSource: 接收數(shù)據(jù)的url,就是sAjaxSource中指定的地址
aoData:DataTables定義的參數(shù),是一個(gè)數(shù)組,其中每個(gè)元素是一個(gè)name-value對(duì),我需要
把客戶名稱這個(gè)參數(shù)加進(jìn)去
fnCallback:服務(wù)器返回?cái)?shù)據(jù)后的處理函數(shù),我需要按DataTables期望的格式傳入返回?cái)?shù)據(jù)
最后自定義的fnServerData如下所示:
// 3個(gè)參數(shù)的名字可以隨便命名,但必須是3個(gè)參數(shù),少一個(gè)都不行

    function retrieveData(sSource, aoData, fnCallback ) {

        $.ajax({

            url : sSource,//這個(gè)就是請(qǐng)求地址對(duì)應(yīng)sAjaxSource

            data : {"aoData":JSON.stringify(aoData)},//這個(gè)是把datatable的一些基本數(shù)據(jù)傳給后臺(tái),比如起始位置,每頁顯示的行數(shù)

            type : 'post',

            dataType : 'json',

            async : false,

            success : function(result) {

                fnCallback(result);//把返回的數(shù)據(jù)傳給這個(gè)方法就可以了,datatable會(huì)自動(dòng)綁定數(shù)據(jù)的

            },

            error : function(msg) {
                alert(msg);
            }

        });

    }

2.后臺(tái)服務(wù)器
2.1 實(shí)體類

    public class User{
    private String firstName;
    private String lastName;
    ...
    getter and setter
    ...
  }

2.2 Controller

@Controller
@RequestMapping("/users")
public class ItemController {
   
    @RequestMapping("/list")
    @ResponseBody
    public String listUsers(@RequestParam String aoData, HttpServletRequest request, Model model){
        
        List<User> list = new ArrayList<User>();
        list.add(new Item("jack","123#"));
        list.add(new Item(2,"jack2","1234#"));
        JSONArray ja = JSONArray.parseArray(aoData);
        String sEcho = null;
        int iDisplayStart = 0;
        int iDisplayLength = 0;
        for (int i = 0; i <ja.size() ; i++) {
            JSONObject jobj = ja.getJSONObject(i);
            if (jobj.get("name").equals("sEcho"))
                sEcho = jobj.get("value").toString();
            if (jobj.get("name").equals("iDisplayStart"))
                iDisplayStart = jobj.getIntValue("value");

            if (jobj.get("name").equals("iDisplayLength"))
                iDisplayLength = jobj.getIntValue("value");
        }
        JSONObject getObj = new JSONObject();
        getObj.put("sEcho",sEcho);
        getObj.put("iTotalRecords",2);
        getObj.put("iTotalDisplayRecords", 2);//顯示的行數(shù),這個(gè)要和上面寫的一樣
        getObj.put("data",list);
            return  getObj.toString();

//        return  list;
    }
}

服務(wù)器端返回的JSON數(shù)據(jù)格式是規(guī)定好的,詳見https://datatables.net/examples/server_side/post.html
格式類似于:

{
  "draw": 1,
  "recordsTotal": 57,
  "recordsFiltered": 57,
  "data": [
    {
      "first_name": "Airi",
      "last_name": "Satou",
      "position": "Accountant",
      "office": "Tokyo",
      "start_date": "28th Nov 08",
      "salary": "$162,700"
    },
    {
      "first_name": "Angelica",
      "last_name": "Ramos",
      "position": "Chief Executive Officer (CEO)",
      "office": "London",
      "start_date": "9th Oct 09",
      "salary": "$1,200,000"
    }
  ]
}

其中,data字段的值可以是數(shù)組類型,也可以是對(duì)象。具體操作查看官網(wǎng)說明。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,533評(píng)論 19 139
  • 點(diǎn)擊查看原文 Web SDK 開發(fā)手冊(cè) SDK 概述 網(wǎng)易云信 SDK 為 Web 應(yīng)用提供一個(gè)完善的 IM 系統(tǒng)...
    layjoy閱讀 14,299評(píng)論 0 15
  • AJAX 原生js操作ajax 1.創(chuàng)建XMLHttpRequest對(duì)象 var xhr = new XMLHtt...
    碧玉含香閱讀 3,557評(píng)論 0 7
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,637評(píng)論 18 399
  • 一、關(guān)于推薦序 1.慢下來,用戰(zhàn)略的眼光看清楚再行動(dòng)。 的確,身處于這個(gè)時(shí)代的我深切地感受到被大量信息包圍。就拿微...
    冰_冰_閱讀 251評(píng)論 0 0

友情鏈接更多精彩內(nèi)容