datatables+java實現服務器端分頁,排序,查詢,列的顯示隱藏

最近看了下datatables,模仿寫了一個小例子,和你們分享一下。效果圖以下javascript

jsp代碼:css

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
<%  
String path = request.getContextPath();  
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
%>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
<head>  
<base href="<%=basePath%>">  
<title>快遞公司列表</title>  
<meta http-equiv="pragma" content="no-cache">  
<meta http-equiv="cache-control" content="no-cache">  
<meta http-equiv="expires" content="0">  
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
<meta http-equiv="description" content="This is my page">  
<link rel="stylesheet" type="text/css" href="css/jquery.dataTables.css">  
<script type="text/javascript" charset="utf8" src="js/jquery-1.9.1.min.js"></script>  
<script type="text/javascript" charset="utf8" src="js/jquery.dataTables.js"></script>  
<script type="text/javascript">  
    var rootPath = '${pageContext.request.contextPath}';  
</script>  
</head>  
<body>  
    <form>  
        <span>編號:</span> <input type="text" placeholder="編號" id="id-search">  
        <span>名稱:</span> <input type="text" placeholder="名稱" id="name-search">  
        <span>狀態:</span> <select id="status-search">  
            <option value="">所有</option>  
            <option value="1">能夠查發</option>  
            <option value="2">能夠連接</option>  
            <option value="3">僅供查詢</option>  
            <option value="4">不可用</option>  
        </select>  
        <button type="button" id="btn_search">查詢</button>  
          
        <a href="#" data-column="0">影藏編號</a>  
        <a href="#" data-column="1">影藏名稱</a>  
        <a href="#" data-column="2">影藏狀態</a>  
        <a href="#" data-column="3">影藏電話</a>  
        <a href="#" data-column="4">影藏網址</a>  
        <a href="#" data-column="5">影藏操做</a>  
    </form>  
    <table id="table" class="display">  
        <thead>  
            <tr>  
                <th>編號</th>  
                <th>名稱</th>  
                <th>狀態</th>  
                <th>電話</th>  
                <th>網址</th>  
                <th>操做</th>  
            </tr>  
        </thead>  
        <tbody></tbody>  
    </table>  
    <script type="text/javascript" src="js/constant.js"></script>  
    <script type="text/javascript">  
    $(function(){  
        var $table = $("#table");  
        var _table = $table.dataTable($.extend(true,{},CONSTANT.DATA_TABLES.DEFAULT_OPTION, {  
            ajax : function(data, callback, settings) {  
                //封裝請求參數  
                var param = userManage.getQueryCondition(data);  
                $.ajax({  
                        type: "GET",  
                        url: rootPath+"/carrier/getCarrierByPage.action",  
                        cache : false,  //禁用緩存  
                        data: param,    //傳入已封裝的參數  
                        dataType: "json",  
                        success: function(result) {  
                                //異常判斷與處理  
                                if (result.errorCode) {  
                                    alert("查詢失敗");  
                                    return;  
                                }  
                                //封裝返回數據  
                                var returnData = {};  
                                returnData.draw = data.draw;//這裏直接自行返回了draw計數器,應該由後臺返回  
                                returnData.recordsTotal = result.total;//總記錄數  
                                returnData.recordsFiltered = result.total;//後臺不實現過濾功能,每次查詢均視做所有結果  
                                returnData.data = result.pageData;  
                                //調用DataTables提供的callback方法,表明數據已封裝完成並傳回DataTables進行渲染  
                                //此時的數據需確保正確無誤,異常判斷應在執行此回調前自行處理完畢  
                                callback(returnData);  
                        },  
                        error: function(XMLHttpRequest, textStatus, errorThrown) {  
                            alert("查詢失敗");  
                        }  
                    });  
            },  
            //綁定數據  
            columns: [  
                {  
                    data: "carrierId",//字段名  
                },  
                {  
                    data: "carrierName",//字段名  
                },  
                {  
                    data : "carrierStatus",//字段名  
                    render : function(data,type, row, meta) {  
                        return (data == 1? "能夠查發":data == 2?"能夠連接":data == 3?"僅供查詢":"不可用");  
                    }  
                },  
                {  
                    data : "carrierPhone",//字段名  
                },  
                {  
                    data : "carrierLink",//字段名  
                    orderable : false,//禁用排序  
                    render : CONSTANT.DATA_TABLES.RENDER.ELLIPSIS//alt效果  
                },  
                 {  
                    data: null,//字段名  
                    defaultContent:"",//無默認值  
                    orderable : false//禁用排序  
                }  
            ],  
            "createdRow": function ( row, data, index ) {  
                //不使用render,改用jquery文檔操做呈現單元格  
                var $btnEdit = $('<button type="button" class="btn-edit">修改</button>');  
                var $btnDel = $('<button type="button" class="btn-del">刪除</button>');  
                $('td', row).eq(5).append($btnEdit).append($btnDel);  
            },  
            "drawCallback": function( settings ) {  
                //渲染完畢後的回調  
                //默認選中第一行  
                //$("tbody tr",$table).eq(0).click();  
            }  
        })).api();//此處需調用api()方法,不然返回的是JQuery對象而不是DataTables的API對象  
        //查詢  
        $("#btn_search").click(function(){  
            _table.draw();  
        });  
        //行點擊事件  
        $("tbody",$table).on("click","tr",function(event) {  
            $(this).addClass("active").siblings().removeClass("active");  
            //獲取該行對應的數據  
            var item = _table.row($(this).closest('tr')).data();  
            userManage.showItemDetail(item);  
        });  
        //按鈕點擊事件  
        $table.on("click",".btn-edit",function() {  
            //點擊編輯按鈕  
            var item = _table.row($(this).closest('tr')).data();  
            userManage.editItemInit(item);  
        }).on("click",".btn-del",function() {  
            //點擊刪除按鈕  
            var item = _table.row($(this).closest('tr')).data();  
            userManage.deleteItem(item);  
        });  
        //影藏列  
        $('a').on( 'click', function (e) {  
            var cut = $(this).text()  
            if(cut.indexOf("顯示")>-1){  
                $(this).text("影藏"+cut.split("示")[1])  
            }else{  
                $(this).text("顯示"+cut.split("藏")[1])  
            }  
            e.preventDefault();  
            var column = _table.column( $(this).attr('data-column') );  
            column.visible( ! column.visible() );  
        } );  
          
    });  
    var userManage = {  
            getQueryCondition : function(data) {  
                var param = {};  
                //組裝排序參數  
                if (data.order&&data.order.length&&data.order[0]) {  
                    switch (data.order[0].column) {  
                    case 0:  
                        param.orderColumn = "carrier_id";//數據庫列名稱  
                        break;  
                    case 1:  
                        param.orderColumn = "carrier_name";//數據庫列名稱  
                        break;  
                    case 2:  
                        param.orderColumn = "carrier_status";//數據庫列名稱  
                        break;  
                    case 3:  
                        param.orderColumn = "carrier_phone";//數據庫列名稱  
                        break;  
                    default:  
                        param.orderColumn = "carrier_id";//數據庫列名稱  
                        break;  
                    }  
                    //排序方式asc或者desc  
                    param.orderDir = data.order[0].dir;  
                }  
                param.id = $("#id-search").val();//查詢條件  
                param.name = $("#name-search").val();//查詢條件  
                param.status = $("#status-search").val();//查詢條件  
                //組裝分頁參數  
                param.startIndex = data.start;  
                param.pageSize = data.length;  
                param.draw = data.draw;  
                return param;  
            },  
            editItemInit : function(item) {  
                //編輯方法  
                alert("編輯"+item.carrierId+"  "+item.carrierName);  
            },  
            deleteItem : function(item) {  
                //刪除  
                alert("刪除"+item.carrierId+"  "+item.carrierName);     
            },  
            showItemDetail: function(item){  
                //點擊行  
                alert("點擊"+item.carrierId+"  "+item.carrierName);  
            }  
        };  
   </script>  
</body>  
</html>

其他js和css都是datatables官方提供的html

constants.jsjava

/*常量*/  
var CONSTANT = {  
        DATA_TABLES : {  
            DEFAULT_OPTION : { //DataTables初始化選項  
                language: {  
                    "sProcessing":   "處理中...",  
                    "sLengthMenu":   "每頁 _MENU_ 項",  
                    "sZeroRecords":  "沒有匹配結果",  
                    "sInfo":         "當前顯示第 _START_ 至 _END_ 項,共 _TOTAL_ 項。",  
                    "sInfoEmpty":    "當前顯示第 0 至 0 項,共 0 項",  
                    "sInfoFiltered": "(由 _MAX_ 項結果過濾)",  
                    "sInfoPostFix":  "",  
                    "sSearch":       "搜索:",  
                    "sUrl":          "",  
                    "sEmptyTable":     "表中數據爲空",  
                    "sLoadingRecords": "載入中...",  
                    "sInfoThousands":  ",",  
                    "oPaginate": {  
                        "sFirst":    "首頁",  
                        "sPrevious": "上頁",  
                        "sNext":     "下頁",  
                        "sLast":     "末頁",  
                        "sJump":     "跳轉"  
                    },  
                    "oAria": {  
                        "sSortAscending":  ": 以升序排列此列",  
                        "sSortDescending": ": 以降序排列此列"  
                    }  
                },  
                autoWidth: false,   //禁用自動調整列寬  
                stripeClasses: ["odd", "even"],//爲奇偶行加上樣式,兼容不支持CSS僞類的場合  
                order: [],          //取消默認排序查詢,不然複選框一列會出現小箭頭  
                processing: false,  //隱藏加載提示,自行處理  
                serverSide: true,   //啓用服務器端分頁  
                searching: false    //禁用原生搜索  
            },  
            COLUMN: {  
                CHECKBOX: { //複選框單元格  
                    className: "td-checkbox",  
                    orderable: false,  
                    width: "30px",  
                    data: null,  
                    render: function (data, type, row, meta) {  
                        return '<input type="checkbox" class="iCheck">';  
                    }  
                }  
            },  
            RENDER: {   //經常使用render能夠抽取出來,如日期時間、頭像等  
                ELLIPSIS: function (data, type, row, meta) {  
                    data = data||"";  
                    return '<span title="' + data + '">' + data + '</span>';  
                }  
            }  
        }  
};

後臺代碼:jquery

@RequestMapping(value = "/getCarrierByPage")  
    @ResponseBody  
    public String getCarrierByPage() throws Exception{  
        //直接返回前臺  
        String draw = request.getParameter("draw");  
        //數據起始位置  
        String startIndex = request.getParameter("startIndex");  
        //每頁顯示的條數  
        String pageSize = request.getParameter("pageSize");  
        //獲取排序字段  
        String orderColumn = request.getParameter("orderColumn");  
        if(orderColumn == null){  
            orderColumn = "carrier_id";  
        }  
        //獲取排序方式  
        String orderDir = request.getParameter("orderDir");  
        if(orderDir == null){  
            orderDir = "asc";  
        }  
        //查詢條件  
        String carrierId = request.getParameter("id");  
        String carrierName = request.getParameter("name");  
        String carrierStatus = request.getParameter("status");  
        XcxCarrier x = new XcxCarrier();  
        if(null != carrierId && !"".equals(carrierId)){  
            x.setCarrierId(Long.parseLong(carrierId));  
        }  
        x.setCarrierName(carrierName);  
        if(null != carrierStatus && !"".equals(carrierStatus)){  
            x.setCarrierStatus(Integer.parseInt(carrierStatus));  
        }  
        PageHelper.offsetPage(getPageNo(Integer.parseInt(startIndex)), getPageSize(Integer.parseInt(pageSize)));  
        List<XcxCarrier> result = this.xcxCarrierService.querySelectByCondition(orderColumn, orderDir, x);  
        PageInfo<XcxCarrier> pageInfo = new PageInfo<XcxCarrier>(result);  
        Map<Object, Object> info = new HashMap<Object, Object>();  
        System.out.println(JSONObject.fromObject(pageInfo));  
        info.put("pageData", pageInfo.getList());  
        info.put("total", pageInfo.getTotal());  
        info.put("draw", draw);  
        return JSONObject.fromObject(info)+"";  
    }
相關文章
相關標籤/搜索