1. 程式人生 > >springmvc + jquery datatable + ajax實現服務端動態分頁查詢

springmvc + jquery datatable + ajax實現服務端動態分頁查詢

一、實現目標,如上圖所示

二、需要匯入的js和css如下

       1、 jquery.dataTables.css 

       2、jquery.js  

       3、 jquery.dataTables.js

三、jsp頁面(datatableTest.jsp)

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%String ctx = request.getContextPath(); %>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="${ctx }datatable/js/jquery.js"></script>
<script src="${ctx }datatable/js/jquery.dataTables.js"></script>
<link rel="stylesheet" href="${ctx }datatable/css/jquery.dataTables.css" type="text/css">
<title>Insert title here</title>
</head>
<body>
       <table id="tb" class="display">
            <thead>
                <tr>
                    <th>col1</th>
                    <th>col2</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
        <script type="text/javascript">
        $(document).ready(function() {
            $("#tb").dataTable({  
                "bProcessing": false, // 是否顯示取資料時的那個等待提示
                "bServerSide": true,//這個用來指明是通過服務端來取資料
                "sAjaxSource": "${ctx}datatable/getAlltable",//這個是請求的地址
                "fnServerData": retrieveData // 獲取資料的處理函式
            });
        });
         
        // 3個引數的名字可以隨便命名,但必須是3個引數,少一個都不行
        function retrieveData( sSource111,aoData111, fnCallback111) {
            $.ajax({
                url : sSource111,//這個就是請求地址對應sAjaxSource
                data : {"aoData":JSON.stringify(aoData111)},//這個是把datatable的一些基本資料傳給後臺,比如起始位置,每頁顯示的行數
                type : 'post',
                dataType : 'json',
                async : false,
                success : function(result) {
                    fnCallback111(result);//把返回的資料傳給這個方法就可以了,datatable會自動繫結資料的
                },
                error : function(msg) {
                }
            });
        }
    </script>
</body>
</html>
四、後端程式碼(DataTableController.java)
package com.ctvit.example.dataTable.web;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class DataTableController {

    @RequestMapping("/go-datatable")
    public ModelAndView go_datatable(){
        return new ModelAndView("datatable/datatableTest");
    }
    
    @RequestMapping("/datatable/getAlltable")
    @ResponseBody
    public String getAlltable(@RequestParam String aoData){
        JSONArray jsonarray = JSONArray.fromObject(aoData);
         
        String sEcho = null;
        int iDisplayStart = 0; // 起始索引
        int iDisplayLength = 0; // 每頁顯示的行數
     
        for (int i = 0; i < jsonarray.size(); i++) {
            JSONObject obj = (JSONObject) jsonarray.get(i);
            if (obj.get("name").equals("sEcho"))
                sEcho = obj.get("value").toString();
     
            if (obj.get("name").equals("iDisplayStart"))
                iDisplayStart = obj.getInt("value");
     
            if (obj.get("name").equals("iDisplayLength"))
                iDisplayLength = obj.getInt("value");
        }
     
        // 生成20條測試資料
        List<String[]> lst = new ArrayList<String[]>();
        for (int i = 0; i < 20; i++) {
            String[] d = { "co1_data" + i, "col2_data" + i };
            lst.add(d);
        }
         
        JSONObject getObj = new JSONObject();
        getObj.put("sEcho", sEcho);// 不知道這個值有什麼用,有知道的請告知一下
        getObj.put("iTotalRecords", lst.size());//實際的行數
        getObj.put("iTotalDisplayRecords", lst.size());//顯示的行數,這個要和上面寫的一樣
         
        getObj.put("aaData", lst.subList(iDisplayStart,iDisplayStart + iDisplayLength));//要以JSON格式返回
        System.out.println(getObj.toString());
        return getObj.toString();
    }
}