DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> 基於SpringMVC+Bootstrap+DataTables實現表格服務端分頁、模糊查詢
基於SpringMVC+Bootstrap+DataTables實現表格服務端分頁、模糊查詢
編輯:關於JavaScript     

前言

基於SpringMVC+Bootstrap+DataTables實現數據表格服務端分頁、模糊查詢(非DataTables Search),頁面異步刷新。

說明:sp:message標簽是使用了SpringMVC國際化

效果

DataTable表格

這裡寫圖片描述

關鍵字查詢

自定義關鍵字查詢,非DataTable Search

這裡寫圖片描述

代碼

HTML代碼

查詢條件代碼

<!-- 查詢、添加、批量刪除、導出、刷新 -->
<div class="row-fluid">
<div class="pull-right">
<div class="btn-group">
<button type="button" class="btn btn-primary btn-sm" id="btn-add">
<i class="fa fa-plus"></i> <sp:message code="sys.add"/>
</button>
<button type="button" class="btn btn-primary btn-sm" id="btn-delAll">
<i class="fa fa-remove"></i> <sp:message code="sys.delAll"/>
</button>
<button type="button" class="btn btn-primary btn-sm" id="btn-export">
<i class="fa fa-sign-in"></i> <sp:message code="sys.export"/>
</button>
<button type="button" class="btn btn-primary btn-sm" id="btn-re">
<i class="fa fa-refresh"></i> <sp:message code="sys.refresh"/>
</button>
</div>
</div>
<div class="row">
<form id="queryForm" action="<%=path%>/goodsType/list" method="post">
<div class="col-xs-2">
<input type="text" id="keyword" name="keyword" class="form-control input-sm"
placeholder="<sp:message code="sys.keyword"/>">
</div>
<button type="button" class="btn btn-primary btn-sm" id="btn-query">
<i class="fa fa-search"></i> <sp:message code="sys.query"/>
</button>
</form>
</div>
</div>

數據table代碼

<table id="dataTable" class="table table-striped table-bordered table-hover table-condensed" align="center">
<thead>
<tr class="info">
<td><input type="checkbox" id="checkAll"></td>
<th><sp:message code="sys.no"/></th>
<th><sp:message code="goods.type.name.cn"/></th>
<th><sp:message code="goods.type.name.en"/></th>
<th><sp:message code="sys.create.time"/></th>
<th><sp:message code="sys.update.time"/></th>
<th><sp:message code="sys.oper"/></th>
</tr>
</thead>
</table>

JS代碼

DataTables初始化、服務端數據請求、查詢條件封裝

<!-- page script -->
<script>
$(function () {
//添加、修改異步提交地址
var url = "";
var tables = $("#dataTable").dataTable({
serverSide: true,//分頁,取數據等等的都放到服務端去
processing: true,//載入數據的時候是否顯示“載入中”
pageLength: 10, //首次加載的數據條數
ordering: false, //排序操作在服務端進行,所以可以關了。
pagingType: "full_numbers",
autoWidth: false,
stateSave: true,//保持翻頁狀態,和comTable.fnDraw(false);結合使用
searching: false,//禁用datatables搜索
ajax: { 
type: "post",
url: "<%=path%>/goodsType/getData",
dataSrc: "data",
data: function (d) {
var param = {};
param.draw = d.draw;
param.start = d.start;
param.length = d.length;
var formData = $("#queryForm").serializeArray();//把form裡面的數據序列化成數組
formData.forEach(function (e) {
param[e.name] = e.value;
});
return param;//自定義需要傳遞的參數。
},
},
columns: [//對應上面thead裡面的序列
{"data": null,"width":"10px"},
{"data": null},
{"data": 'typeNameCn' },
{"data": 'typeNameEn' },
{"data": 'createTime', 
"render":function(data,type,full,callback) {
return data.substr(0,19) 
}
},
{"data": 'updateTime', defaultContent: "", 
"render":function(data,type,full,callback) {
if(data != null && data != ""){
return data.substr(0,19) 
}else{
return data;
}
}
},
{"data": null,"width":"60px"}
],
//操作按鈕
columnDefs: [
{
targets: 0,
defaultContent: "<input type='checkbox' name='checkList'>"
},
{
targets: -1,
defaultContent: "<div class='btn-group'>"+
"<button id='editRow' class='btn btn-primary btn-sm' type='button'><i class='fa fa-edit'></i></button>"+
"<button id='delRow' class='btn btn-primary btn-sm' type='button'><i class='fa fa-trash-o'></i></button>"+
"</div>"
}
],
language: {
lengthMenu: "",
processing: "<sp:message code='sys.load'/>",
paginate: {
previous: "<",
next: ">",
first: "<<",
last: ">>"
},
zeroRecords: "<sp:message code='sys.nodata'/>",
info: "<sp:message code='sys.pages'/>",
infoEmpty: "",
infoFiltered: "",
sSearch: "<sp:message code='sys.keyword'/>:",
},
//在每次table被draw完後回調函數
fnDrawCallback: function(){
var api = this.api();
//獲取到本頁開始的條數
   var startIndex= api.context[0]._iDisplayStart;
   api.column(1).nodes().each(function(cell, i) {
     cell.innerHTML = startIndex + i + 1;
   }); 
}
});
//查詢按鈕
$("#btn-query").on("click", function () {
tables.fnDraw();//查詢後不需要保持分頁狀態,回首頁
});
//添加
$("#btn-add").on("click", function () {
url = "<%=path%>/goodsType/add";
$("input[name=typeId]").val(0);
$("input[name=typeNameCn]").val("");
$("input[name=typeNameEn]").val("");
$("#editModal").modal("show");
});
//批量刪除
$("#btn-delAll").on("click", function () {
});
//導出
$("#btn-export").on("click", function () {
});
//刷新
$("#btn-re").on("click", function () {
tables.fnDraw(false);//刷新保持分頁狀態
});
//checkbox全選
$("#checkAll").on("click", function () {
if ($(this).prop("checked") === true) {
$("input[name='checkList']").prop("checked", $(this).prop("checked"));
//$("#dataTable tbody tr").addClass('selected');
$(this).hasClass('selected')
} else {
$("input[name='checkList']").prop("checked", false);
$("#dataTable tbody tr").removeClass('selected');
}
});
//修改
$("#dataTable tbody").on("click", "#editRow", function () {
var data = tables.api().row($(this).parents("tr")).data();
$("input[name=typeId]").val(data.typeIdStr);
$("input[name=typeNameCn]").val(data.typeNameCn);
$("input[name=typeNameEn]").val(data.typeNameEn);
url = "<%=path%>/goodsType/update";
$("#editModal").modal("show");
});
$("#btn-submit").on("click", function(){
$.ajax({
cache: false,
type: "POST",
url: url,
data:$("#editForm").serialize(),
async: false,
error: function(request) {
showFail("Server Connection Error...");
},
success: function(data) {
if(data.status == 1){
$("#editModal").modal("hide");
showSuccess("<sp:message code='sys.oper.success'/>");
tables.fnDraw();
}else{
showFail("<sp:message code='sys.oper.fail'/>");
}
}
});
});
//刪除
$("#dataTable tbody").on("click", "#delRow", function () {
var data = tables.api().row($(this).parents("tr")).data();
if(confirm("是否確認刪除這條信息?")){
$.ajax({
url:'<%=path%>/goodsType/del/'+data.typeIdStr,
type:'delete',
dataType: "json",
cache: "false",
success:function(data){
if(data.status == 1){
showSuccess("<sp:message code='sys.oper.success'/>");
tables.api().row().remove().draw(false);
}else{
showFail("<sp:message code='sys.oper.fail'/>");
}
},
error:function(err){
showFail("Server Connection Error...");
}
});
}
});
});
</script>

Java代碼

Controller處理方法,負責查詢頁面需要表格數據,格式化Json後返回。

@RequestMapping(value="/goodsType/getData", produces = "text/json;charset=UTF-8")
@ResponseBody
public String getData(HttpServletRequest request, QueryCondition query) {
DatatablesView<GoodsType> dataTable = goodsTypeService.getGoodsTypeByCondition(query);
dataTable.setDraw(query.getDraw());
String data = JSON.toJSONString(dataTable);
return data;
}

返回Json數據格式

{
"data": [{
"createTime": "2016-10-27 09:42:28.0",
"typeId": 96824775296417986,
"typeIdStr": "96824775296417986",
"typeNameCn": "食品",
"typeNameEn": "Foods",
"updateTime": "2016-10-28 13:00:24.0"
},
{
"createTime": "2016-10-27 09:42:27.0",
"typeId": 96824775296417979,
"typeIdStr": "96824775296417979",
"typeNameCn": "汽車",
"typeNameEn": "Cars123",
"updateTime": "2016-10-27 09:51:24.0"
}],
"draw": 1,
"recordsFiltered": 17,
"recordsTotal": 17
}

DatatablesView,根據DataTables需要格式定義

public class DatatablesView<T> { 
private List<T> data; //data 與datatales 加載的“dataSrc"對應 
private int recordsTotal; 
private int recordsFiltered; 
private int draw;
public DatatablesView() { 
}
public int getDraw() {
return draw;
}
public void setDraw(int draw) {
this.draw = draw;
}
public List<T> getData() {
return data;
}
public void setData(List<T> data) {
this.data = data;
}
public int getRecordsTotal() {
return recordsTotal;
}
public void setRecordsTotal(int recordsTotal) {
this.recordsTotal = recordsTotal;
this.recordsFiltered = recordsTotal;
}
public int getRecordsFiltered() {
return recordsFiltered;
}
public void setRecordsFiltered(int recordsFiltered) {
this.recordsFiltered = recordsFiltered;
} 
}

Service業務處理類,主要根據查詢條件統計記錄數量,查詢當前頁數據列表

public DatatablesView<GoodsType> getGoodsTypeByCondition(QueryCondition query) {
DatatablesView<GoodsType> dataView = new DatatablesView<GoodsType>();
//構建查詢條件
WherePrams where = goodsTypeDao.structureConditon(query);
Long count = goodsTypeDao.count(where);
List<GoodsType> list = goodsTypeDao.list(where);
dataView.setRecordsTotal(count.intValue());
dataView.setData(list);
return dataView;
}

Dao層就是基本的數據庫查詢操作,這裡省略…

結尾

查詢條件這裡只使用了關鍵字模糊查詢,根據業務需要,可以動態加入其他查詢條件,後台需要做相應處理。

以上所述是小編給大家介紹的基於SpringMVC+Bootstrap+DataTables實現表格服務端分頁、模糊查詢,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved