datatables表格外掛實現前後端排序+分頁+條件查詢
阿新 • • 發佈:2019-02-09
1、在頁面中引入datatables需要的js及css檔案,定義一個表格
<link rel="stylesheet" href="/script/libs/DataTables/datatables.min.css" type="text/css" /> <link rel="stylesheet" href="/script/c_hr_employee.css"> <script type="text/javascript" src="/script/libs/jquery-1.8.3.js" ></script> <script type="text/javascript" src="/script/libs/DataTables/datatables.min.js"></script> <script type="text/javascript" src="/script/libs/DataTables/constant.js" ></script> <script type="text/javascript" src="/script/l_hr_employee.js" ></script> <div id="dv_eeFind" style="left: 15px;"> <form id="eeFind_form"> 賬號 <input type="text" name="username" class="myinput" /> 姓名 <input type="text" name="employee.name" class="myinput" /> 工號 <input type="text" name="employee.num" class="myinput" /> 部門 <select id="dept" name="employee.deptId" class="myselectt"> <option selected="selected" disabled="disabled" style="display: none;" value="">選擇部門</option> <c:forEach items="${depts }" var="dept"> <option value="${dept.id }">${dept.name }</option> </c:forEach> </select> 狀態 <select id="status" name="employee.status" class="myselectt"> <option selected="selected" disabled="disabled" style="display: none;" value="">選擇狀態</option> <c:forEach items="${jobStatus }" var="status"> <option value="${status.kid }">${status.item }</option> </c:forEach> </select><br/> 工作性質 <select id="jtype" name="employee.jtype" class="myselectt"> <option selected="selected" disabled="disabled" style="display: none;" value="">選擇類別</option> <c:forEach items="${jobCategory }" var="jtype"> <option value="${jtype.kid }">${jtype.item }</option> </c:forEach> </select> 入職日期 <input type="text" name="edate" class="myinput Wdate" onclick="WdatePicker({dateFmt:'yyyy-MM',readOnly:true})" style="width: 120px;" /> 轉正日期 <input type="text" name="jdate" class="myinput Wdate" onclick="WdatePicker({dateFmt:'yyyy-MM',readOnly:true})" style="width: 120px;margin-top: 10px;" /> <!-- onpicked:pageQueryEmployee表示當我們選擇了時間後,就會觸發事件,執行pageQueryEmployee()js函式中的功能 --> 離職日期 <input type="text" name="ddate" class="myinput Wdate" onclick="WdatePicker({dateFmt:'yyyy-MM',readOnly:true})" style="width: 120px;" /> 生日月份 <input type="text" name="bmonth" class="myinput Wdate" onclick="WdatePicker({dateFmt:'MM',readOnly:true})" style="width: 120px;" /> <a id="eeQueryBtn" type="button" class="bg_btn" >查詢</a> </form> </div> <div id="dv_eeTable" class="table-responsive"> <!-- 顯示入職員工基本資訊表格-start --> <div id="einfo_table"> <table id="eeInfoTable" class="table table-striped table-bordered table-condensed order_table"> <thead> <tr> <th class='text-center' id="e_num">工號</th> <th class='text-center' id="e_name">姓名 </th> <th class='text-center' id="e_uname">賬號 </th> <th class='text-center' id="e_dept_name">部門 </th> <th class='text-center' id="e_job_name">職位 </th> <th class='text-center' id="e_sex">性別 </th> <th class='text-center' id="e_tel">聯絡電話</th> <th class='text-center' id="e_bd">出生年月</th> <th class='text-center' id="e_edate">入職日期</th> <th class='text-center' id="e_status">在職狀態</th> <th class='text-center' id="e_jtype">工作性質</th> <th class='text-center' >操作</th> </tr> </thead> <tbody> </tbody> </table> </div> </div>
2、頁面分頁+排序+條件查詢js程式碼
$(function(){ var $table = $("#entryInfoTable"); 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: "/entry/getEmployeeEntryInfos", 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: "name",//欄位名 orderable : false, render : function(data,type, row, meta) { if(data.state==1){ return data.value; }else if(data.state==0){ return ""; } } }, { data: "dept_name",//欄位名 render : function(data,type, row, meta) { if(data.state==1){ return data.value; }else if(data.state==0){ return ""; } } }, { data : "job_name",//欄位名 render : function(data,type, row, meta) { if(data.state==1){ return data.value; }else if(data.state==0){ return ""; } } }, { data : "num",//欄位名 orderable : false, render : function(data,type, row, meta) { if(data.state==1){ return data.value; }else if(data.state==0){ return ""; } } }, { data : "uname",//欄位名 orderable : false,//禁用排序 render : function(data,type, row, meta) { if(data.state==1){ return data.value; }else if(data.state==0){ return ""; } } }, { data: "status",//欄位名 defaultContent:"",//無預設值 render : function(data,type, row, meta) { if(data.state==1){ return (data.value == 1? "入職":data.value == 2?"轉正":data.value == 3?"離職":" "); }else if(data.state==0){ return ""; } } }, { data : "pdate",//欄位名 render : function(data,type, row, meta) { if(data.state==1){ return data.value; }else if(data.state==0){ return ""; } } }, { data: null,//欄位名 defaultContent:"",//無預設值 orderable : false,//禁用排序 } ], "createdRow": function ( row, data, index ) { //不使用render,改用jquery文件操作呈現單元格 var $opBtn = $('<a class="bg_btn" data_code="2" data_eid="'+data.eid.value+'">完善入職資料</a>'); $('td', row).eq(7).append($opBtn); }, "drawCallback": function( settings ) { //渲染完畢後的回撥 //預設選中第一行 //$("tbody tr",$table).eq(0).click(); } })).api();//此處需呼叫api()方法,否則返回的是JQuery物件而不是DataTables的API物件 //查詢 $("#queryBtn").click(function(){ _table.draw(); }); //查詢表單中的select框值發生變化時執行的事件 $("#deptId").change(function(){ _table.draw(); }); //按鈕點選事件 $table.on("click","a[data_code='2']",function() { //點選完善入職質料按鈕所執行的事件 var eid = this.getAttribute("data_eid") $("#entryFormModal").find('.modal-title').text("完善員工入職資料"); $("#entryFormModal .modal-body").load("/script/v_hr_inleaving_form.jsp?code="+2+"&eid="+eid); $("#entryFormModal").modal(); }); }); var userManage = { getQueryCondition : function(data) { var param = {}; //組裝排序引數 if (data.order&&data.order.length&&data.order[0]) { switch (data.order[0].column) { case 1: param.orderColumn = "dept";//資料庫列名稱 break; case 2: param.orderColumn = "job";//資料庫列名稱 break; case 5: param.orderColumn = "iostatus";//資料庫列名稱 break; case 6: param.orderColumn = "pdate";//資料庫列名稱 break; default: param.orderColumn = "pdate";//資料庫列名稱 break; } //排序方式asc或者desc param.orderDir = data.order[0].dir; } param.username = $("#username").val();//查詢條件 param["employee.name"]= $("#ename").val();//查詢條件 param["employee.num"] = $("#num").val();//查詢條件 param["employee.deptId"] = $("#deptId").val(); param["employee.jobId"] = $("#jobId").val(); param.iostatus = $("#iostatus").val(); param.minPdate = $("#minPdate").val(); param.maxPdate = $("#maxPdate").val(); //組裝分頁引數 param.startIndex = data.start; param.pageSize = data.length; param.draw = data.draw; return param; } };
3、constant.js初始化表格的一些屬性,引數值
/*常量*/ 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, //禁用原生搜尋 lengthChange: false,//關閉選擇每頁顯示的資料條數 paging: true,//允許分頁 info:true,//左下角資訊 showing 1 to 7 of 7entries }, 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>'; } } } };
4、後臺實現排序+分頁+條件查詢的程式碼
Controller層的程式碼
@RequestMapping(value = "/getEmployeeEntryInfos")
public Map<String, Object> getEmployeeEntryInfos(EmployeeEntryInfoExample example,HttpServletRequest request) throws Exception{
//直接返回前臺
String draw = request.getParameter("draw");
//獲取排序欄位
String orderColumn = request.getParameter("orderColumn");
if(orderColumn == null){
orderColumn = "pdate";
}
example.setSortField(orderColumn);
//獲取排序方式
String orderDir = request.getParameter("orderDir");
if(orderDir == null){
orderDir = "asc";
}
example.setSortWay(orderDir);
PageList<List<AuthData>> pageList = employeeEntryInfoService.pageQueryByExample(example, request);
Map<String, Object> info = new HashMap<String, Object>();
info.put("pageData", pageList.getAuthData());
info.put("total", pageList.getTotalCount());
info.put("draw", draw);
return info;
}
service層的程式碼
public PageList<List<AuthData>> pageQueryByExample(EmployeeEntryInfoExample example, HttpServletRequest request){
//資料起始位置
String startIndex = request.getParameter("startIndex");
//每頁顯示的條數
String pageSize = request.getParameter("pageSize");
int totalCount = employeeEntryInfoMapper.selectCountByExample(example);
//判斷總人數是否為0,如果為0就返回一個空的PageList物件,不需要在到資料庫查詢具體的入職員工資訊
if(totalCount == 0){
return new PageList<>();
}else{
//查詢分頁展示的資料
PageHelper.offsetPage((Integer.parseInt(startIndex) / Integer.parseInt(pageSize)) + 1, Integer.parseInt(pageSize));
List<EmployeeEntryInfo> rows = employeeEntryInfoMapper.pageQueryByExample(example);
List<Map<String,AuthData>> dataList = new ArrayList<Map<String,AuthData>>();
for (EmployeeEntryInfo employeeEntryInfo : rows) {
Map<String,AuthData> list = new HashMap<String,AuthData>();
list.put("id",new AuthData("id", employeeEntryInfo.getId(), 0));
list.put("num",new AuthData("num", employeeEntryInfo.getEmployee().getNum(), 1));
list.put("name",new AuthData("name", employeeEntryInfo.getEmployee().getName(), 1));
list.put("dept_name",new AuthData("dept_name", employeeEntryInfo.getEmployee().getDept().getName(), 1));
list.put("job_name",new AuthData("job_name", employeeEntryInfo.getEmployee().getJob().getName(), 1));
list.put("uname",new AuthData("uname", employeeEntryInfo.getEmployee().getAccount().getName(), 1));
list.put("status",new AuthData("status", employeeEntryInfo.getIostatus(), 1));
list.put("pdate",new AuthData("pdate",new SimpleDateFormat("yyyy-MM-dd").format(employeeEntryInfo.getPdate()) , 1));
list.put("eid",new AuthData("eid", employeeEntryInfo.getEid(), 1));
Integer eId = (Integer) request.getSession().getAttribute(DataKey.ACCOUNT_ID.$());
list = AuthData.dataSelect(eId, list);
dataList.add(list);
}
PageList<List<AuthData>> pageList = new PageList<>(totalCount);
pageList.setAuthData(dataList);
return pageList;
}
}
效果圖: