bootstrap-table 預設走的是前端分頁,也就是一次把全部資料拉回瀏覽器再切片。一旦資料量破萬筆,這種做法就會拖垮首屏。本文記錄把它改成服務端分頁的完整流程,包含前端初始化與後端取值兩個部分。
先到官方網站下載 css 與 js 檔,接著在頁面準備好時呼叫初始化函式。關鍵在於 sidePagination 設為 'server',並提供 queryParams 讓我們有機會加工傳出去的查詢參數。
function getTab(){
var url = contextPath+'/fundRetreatVoucher/fundBatchRetreatVoucherQuery.htm';
$('#tab').bootstrapTable({
method: 'get', // 這裡要設為 get
url: url,
cache: false,
height: 400,
striped: true,
pagination: true,
pageList: [10,20],
pageSize: 10,
pageNumber: 1,
search: true,
sidePagination: 'server', // 設置為服務器端分頁
queryParams: queryParams, // 參數
showColumns: true,
showRefresh: true,
minimumCountColumns: 2,
clickToSelect: true,
smartDisplay: true,
columns: [
{ field: 'interfaceInfoCode', title: '資金通道編碼', align: 'center', width: '180', valign: 'bottom', sortable: true },
{ field: 'retreatBatchCode', title: '資金退回批次號', align: 'center', width: '200', valign: 'middle', sortable: true },
{ field: 'total', title: '總筆數', align: 'center', width: '10', valign: 'top', sortable: true },
{ field: 'totalMoney', title: '總金額', align: 'center', width: '100', valign: 'middle', clickToSelect: false },
{ title: '操作', field: 'state', align: 'center', width: '200', valign: 'middle' }
]
});
}
// 設置傳入參數
function queryParams(params) {
return params
}
$(function(){ getTab(); })
這裡要特別提醒:原始範例的註解提到「設成 post 取不到資料」。這通常不是 bootstrap-table 本身的限制,而是後端只實作了 doGet 而沒處理 doPost,把請求方法對齊後端即可,不必被這行註解誤導。
切到服務端分頁後,bootstrap-table 送出的參數名稱會變成 limit(每頁筆數)與 offset(起始位移量),而不是 pageSize、pageNumber。有些教學會建議先做一層格式化轉換,其實直接讀這兩個名字就好。
int currentPage = request.getParameter("offset") == null ? 1 : Integer.parseInt(request.getParameter("offset"));
// 每頁行數
int showCount = request.getParameter("limit") == null ? 10 : Integer.parseInt(request.getParameter("limit"));
if (currentPage != 0) { // 換算成頁碼
currentPage = currentPage / showCount;
}
currentPage += 1;
JSONObject json = new JSONObject();
json.put("rows", bfrv); // rows 與 total 這兩個 key 是固定名稱,不可更改
json.put("total", total);
bootstrap-table 認得死的兩個欄位名稱是 rows 與 total:前者是這一頁的資料陣列,後者是符合條件的總筆數(不是總頁數)。只要 key 對得上,其餘欄位要加什麼都行。
把 offset 換算成頁碼這段寫法比較直覺,但也可以直接把 offset 與 limit 傳進 SQL 的 LIMIT offset, limit,省一層計算。兩種都行,看你的 DAO 介面怎麼設計。