這篇記錄我在使用 bootstrap-table 過程中整理的一些要點,包含 jQuery 的 $.map、後端分頁對接、欄位格式化與事件綁定。
當 rows 中有很多資料,而我只需要 id 這一欄時,用 $.map 會非常簡潔。
$.map(data, function (item, index) {
return XXX;
})
// 用法總結:
// 把一個陣列依新的規則重新組裝並回傳,結果與原陣列不同。
// 它會遍歷 data 的每個元素,依 return 的計算方式形成新元素,放進回傳的陣列。
var b = $.map([55, 1, 2], function (item, index) {
return { "label": item, "value": index };
});
alert(b[0].label + " " + b[0].value); // 輸出 55 0
要注意 $.map 有個容易踩的行為:回呼若回傳 null 或 undefined,該元素會被從結果中剔除。這在過濾資料時很好用,但如果非預期地回傳空值,就會造成元素數量對不上。
後台我用 SpringMVC 撰寫,做分頁處理時使用了離線查詢(DetachedCriteria)。因為我改用 execute() 並傳入 session,而傳進來的是代理類別的資料,無法在下面這個方法中直接轉型:
/**
* Get an executable instance of <literal>Criteria</literal>,
* to actually run the query.
*/
public Criteria getExecutableCriteria(Session session) {
impl.setSession((SessionImplementor) session);
return impl;
}
正確的做法是在 callback 內部取得 executable 版本:
return (PageBean) getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Criteria criteria = detachedCriteria.getExecutableCriteria(session);
// ...
}
});
關鍵點在於:getExecutableCriteria() 會把 session 寫進 impl 並回傳 impl 本身,因此傳入的 session 必須是真正的 Hibernate Session,而不是 Spring 包裝過的代理物件。我卡在這裡查了很久才找到原因。
我的回傳格式與 bootstrap-table 預期的略有不同:
{
"success": true,
"message": null,
"data": {
"pageSize": 15,
"rows": [
{ "userName": "333", "userType": 333, "password": "333", "id": 11, "indexcode": "333" },
{ "userName": "3", "userType": 333, "password": "333", "id": 5, "indexcode": "33333" }
],
"total": 17,
"totalPage": 2,
"page": 0,
"hasPreviousPage": true,
"hasNextPage": true,
"lastPage": false,
"firstPage": false
}
}
這是因為我統一使用了 ActionResult 包裝所有回應,格式比較一致、後端也比較好寫:
/**
* Created by JetWang on 2016/10/1.
*/
public class ActionResult {
private boolean success;
private String message;
private Object data;
public ActionResult () {}
public ActionResult (boolean success) {
this(success, null, null);
}
// getters / setters ...
}
由於多包了一層,前端就得用 responseHandler 把 res.data 抽出來交給表格。
<%@ include file="./common/common.jsp"%>
<%-- 公共的 bootstrap、jQuery 等引用都在 common.jsp 中處理 --%>
<script src="<%=baseUrl%>/libs/bootstrap-table/dist/bootstrap-table.js"
type="text/javascript"></script>
<script src="<%=baseUrl%>/libs/bootstrap-table/dist/bootstrap-table-locale-all.js"
type="text/javascript"</script>
<link rel="stylesheet"
href="<%=baseUrl%>/libs/bootstrap-table/dist/bootstrap-table.css"
type="text/css">
<div class="container">
<table id="table" data-url="/cms/UserInfo/userInfoPage"></table>
</div>
初始化放在 ready 中,若專案用了 seajs 這類模組化工具,也可以改在模組內部處理:
jQuery(document).ready(function () {
// js 程式碼放在這裡
});
下面的設定與事件都可以查文件或直接看原始碼理解,這裡重點標出幾個我實際調整過的項目(原始碼中已修改過 queryParams 與 responseHandler):
BootstrapTable.DEFAULTS = {
classes: 'table table-hover',
locale: undefined,
height: undefined,
undefinedText: '-',
sortName: undefined,
sortOrder: 'asc',
striped: false,
columns: [[]],
data: [],
dataField: 'rows',
method: 'get',
url: undefined,
cache: true,
contentType: 'application/json;charset=UTF-8', // 補上 utf-8
dataType: 'json',
queryParams: function (params) {
// 這裡可改寫查詢參數名。
// 我後端用的是 pageNo,不喜歡 offset,所以在原始碼中改寫。
// 當然也可以改後端,但那更麻煩。
return params;
},
queryParamsType: 'limit',
// undefined:傳 pageNumber、pageSize、searchText、sortName、sortOrder
// limit:傳 limit、offset、search、sort、order
responseHandler: function (res) {
// ajax 成功後、交給表格前處理回應格式。
// 我的後端多包了一層,所以要在這裡整改。
return res;
},
pagination: false,
sidePagination: 'client', // client 或 server
pageSize: 10,
pageNumber: 1,
pageList: [10, 25, 50, 100],
paginationHAlign: 'right',
paginationVAlign: 'bottom',
search: false,
showColumns: false,
showRefresh: false,
showToggle: false,
smartDisplay: true,
singleSelect: false,
checkboxHeader: true,
sortable: true,
idField: undefined,
uniqueId: undefined,
iconsPrefix: 'glyphicon',
rowStyle: function (row, index) { return {}; },
onAll: function (name, args) { return false; },
onClickRow: function (item, $element) { return false; },
onDblClickRow: function (item, $element) { return false; },
onSort: function (name, order) { return false; },
onCheck: function (row) { return false; },
onUncheck: function (row) { return false; },
onCheckAll: function (rows) { return false; },
onUncheckAll: function (rows) { return false; },
onLoadSuccess: function (data) { return false; },
onLoadError: function (status) { return false; },
onPageChange: function (number, size) { return false; },
onSearch: function (text) { return false; },
onRefresh: function (params) { return false; },
onResetView: function () { return false; }
// 其餘設定項請直接查官方文件
};
最關鍵的兩個是 sidePagination 與 responseHandler:前者決定分頁由前端還是後端處理,後者決定如何把後端回應轉成表格認得的格式。
function initTable () {
$table.bootstrapTable({
striped: true, // 斑馬線
pagination: true, // 啟用分頁
pageSize: 15, // 每頁筆數
pageNumber: 1, // 當前頁
pageList: [10, 15, 20, 25], // 可選筆數
search: false, // 是否啟用搜尋
showColumns: true, // 顯示欄位勾選下拉
showRefresh: true, // 顯示重新整理按鈕
sidePagination: 'server', // 伺服器端分頁
responseHandler: function (res) {
// 回應資料在交給表格前處理
return res.data;
},
queryParamsType: 'undefined',
queryParams: function (params) {
// 自訂查詢參數名,對應我的後端介面
return {
pageNo: params.pageNumber,
pageSize: params.pageSize
};
},
onLoadSuccess: function (data) {
console.log('加載成功', data);
},
onLoadError: function () {
layer.msg('加載數據失敗', { time: 1500, icon: 2 });
},
height: getHeight(),
columns: [
{ field: 'state', checkbox: true, align: 'center', valign: 'middle' },
{ title: 'ID', field: 'id', align: 'center', valign: 'middle' },
{ field: 'userName', title: 'UserName', sortable: true,
footerFormatter: totalNameFormatter, align: 'center' },
{ field: 'userType', title: 'UserType', sortable: true, align: 'center' },
{ field: 'password', title: 'UserPass', sortable: true, align: 'center' },
{ field: 'indexcode', title: 'Indexcode', sortable: true, align: 'center' },
{ field: 'operate', title: 'Item Operate', align: 'center',
events: operateEvents, formatter: operateFormatter }
]
});
}
兩者都是針對當前欄位的顯示做處理,文件中的說明是:
formatter:context(this)是該欄位的 column 物件。函式吃三個參數——value(欄位值)、row(該列資料)、index(列索引)。
footerFormatter:context 同樣是 column 物件。函式吃一個參數 data(所有資料列的陣列),應該回傳要顯示在頁尾儲存格的文字。
以下範例在單一儲存格中放入兩個按鈕:
function operateFormatter (value, row, index) {
return [
'<a class="like" href="javascript:void(0)" title="Like">',
'<i class="glyphicon glyphicon-heart"></i>',
'</a> ',
'<a class="remove" href="javascript:void(0)" title="Remove">',
'<i class="glyphicon glyphicon-remove"></i>',
'</a>'
].join('');
}
也可以在 formatter 中直接寫 inline 事件:
{
title: '操作',
field: 'id',
align: 'center',
formatter: function (value, row, index) {
var e = '<a href="#" onclick="edit(\'' + row.id + '\')">編輯</a> ';
var d = '<a href="#" onclick="del(\'' + row.id + '\')">刪除</a> ';
return e + d;
}
}
不過這種寫法有兩個問題值得注意:一是行內 onclick 在設定 CSP(Content-Security-Policy)的環境下會直接被阻擋;二是把資料拼進 HTML 字串若未做跳脫,會有 XSS 風險。所以官方推薦的做法是改用 events 設定。
官方文件說明:使用 formatter 函式時,儲存格事件監聽器吃四個參數——event(jQuery 事件物件)、value(欄位值)、row(列資料)、index(列索引)。
{
field: 'operate',
title: 'Item Operate',
align: 'center',
events: operateEvents,
formatter: operateFormatter
}
window.operateEvents = {
'click .like': function (e, value, row, index) {
alert('You click like action, row: ' + JSON.stringify(row));
},
'click .remove': function (e, value, row, index) {
$table.bootstrapTable('remove', {
field: 'id',
values: [row.id]
});
}
};
這種寫法把事件與渲染分開,好處很明確:不必把資料拼進 HTML 字串,因此沒有跳脫與 XSS 問題;事件也不會因為表格重繪而失效,因為 bootstrap-table 內部用的是事件代理。
// 兩種寫法
$('#table').bootstrapTable({
onEventName: function (arg1, arg2) {
// ...
}
});
$('#table').on('event-name.bs.table', function (e, arg1, arg2) {
// ...
});
// onAll 會在所有事件觸發時被呼叫
// name: 事件名稱,args: 事件資料
$table.on('all.bs.table', function (e, name, args) {
console.log(name, args);
});
// 呼叫語法
$('#table').bootstrapTable('method', parameter);
// 1. 取得當前勾選的列(未選時回傳空陣列)
getSelections
// 2. 取得所有勾選的列(包含搜尋或篩選後的結果)
getAllSelections
// 3. 移除資料
// params 包含兩個屬性:
// field — 要移除的欄位名
// values — 要移除的值陣列
remove
把「取得勾選」與「移除」組起來,就是一個批次刪除按鈕:
function getIdSelections () {
return $.map($table.bootstrapTable('getSelections'), function (row) {
return row.id;
});
}
$remove.click(function () {
var ids = getIdSelections();
if (ids.length === 0) {
layer.msg('請先選擇要刪除的資料', { icon: 0 });
return;
}
// 這裡只是前端移除;正式環境應先呼叫後端 API 確認刪除成功再更新畫面
$table.bootstrapTable('remove', { field: 'id', values: ids });
$remove.prop('disabled', true);
});
批次刪除不要只更新前端。範例中的 remove 只改動畫面上的資料,重新整理就會回來。正式環境應該先呼叫後端刪除介面,成功後再更新表格,並統一處理部分失敗的情況。
密碼欄位不該出現在列表 API 中。上面的後端回應範例把 password 一起傳給了前端。這是一個真實的安全問題——任何攔截到這個回應的人都能取得所有使用者的密碼。列表介面應該只回傳必要欄位。
sidePagination 決定了很多事。設為 'client' 時所有資料一次載入,排序與篩選都在瀏覽器進行,實作簡單但資料量大時會卡;設為 'server'' 時排序與搜尋都要後端配合處理,複雜但可擴充。選錯了後面改起來很痛,一開始就想清楚。
想更深入學習,可以參考 Bootstrap 的官方文件,並搭配實作練習。
以上是本文的全部內容,希望對大家的學習有所幫助。