DIV CSS 佈局教程網

EasyUI datagrid 後端分頁實作:前端 Ajax 封裝與後端 JSON 對接
編輯:關於JavaScript     

EasyUI 的 datagrid 是企業後台常見的表格元件,但要讓它跑真正的後端分頁,得自己搭一層資料綁定邏輯。本文示範如何把 Ajax 請求、分頁控制項、表單序列化與欄位格式化整合起來,並說明後端必須回傳什麼格式。

步驟一:引入 easyui 的 css 與 js

這步沒什麼學問,把 jquery.min.js、jquery.easyui.min.js 與對應主題樣式表放進頁面即可。

步驟二:前端 JavaScript

這段程式做了四件事:封裝 Ajax、把回傳資料灌進 datagrid 並接管分頁器、把表單序列化成物件、以及處理欄寬自適應。

// 源數據
function Async(action, args, callback){
  $.ajax({
    url: action,
    type: "POST",
    dataType: "json",
    timeout: 10000,
    data: args,
    success: function(data){
      if(callback){ callback(data); }
    }
  });
}

// 綁定數據並設置分頁
function BingData(pid, args, action, callback){
  Async(action, args, function(data){
    if(data != null && data.list != null){
      var _dataCount = data.size; // 總條數
      var _data = data.list;      // 數據
      if(callback){ callback(_data); }
      $(pid).datagrid('loadData', _data);
      $(pid).datagrid('getPager').pagination({
        beforePageText: '第',
        afterPageText: '頁 共 {pages} 頁',
        displayMsg: '當前顯示 {from} - {to} 條記錄 共 {total} 條記錄',
        pageSize: args.pageSize,
        total: _dataCount,
        pageNumber: args.pageIndex,
        pageList: args.pageList,
        onSelectPage: function (pageNumber, pageSize) {
          args.pageIndex = pageNumber;
          args.pageSize = pageSize;
          BingData(pid, args, action, null);
        },
        onRefresh: function (pageNumber, pageSize) {
          args.pageIndex = pageNumber;
          args.pageSize = pageSize;
          BingData(pid, args, action, null);
        }
      });
    }
  });
}

// 表單序列化為對象
$.fn.serializeObject = function(){
  var obj = {};
  $.each(this.serializeArray(), function(i, o){
    var n = o.name, v = o.value;
    obj[n] = obj[n] === undefined ? v
      : ($.isArray(obj[n]) ? obj[n].concat(v) : [obj[n], v]);
  });
  return JSON.stringify(obj);
};

// 寬度
function fixWidth(percent){
  return document.body.clientWidth * percent;
}

// 結束編輯
function endEdit(vid){
  vid = "#" + vid;
  var tb = $(vid);
  var rows = tb.datagrid('getRows');
  for (var i = 0; i < rows.length; i++) {
    tb.datagrid('endEdit', i);
  }
}

function GetData(obj){
  var url = contextPath + '/fundRetreatVoucher/fundBatchRetreatVoucherQuery.htm';
  var args = {};
  args.pageIndex = 1;  // 頁索引
  args.pageSize = 10;  // 頁容量
  if(obj != null){ args.obj = obj; } // 表單序列化的對象
  BingData("#tab", args, url, null);
}

function getTab(){
  GetData();
  var tb = $('#tab');
  tb.datagrid({
    title: '資金退回批次查詢結果',
    fitColumns: true,
    rownumbers: true,
    nowrap: true,
    striped: true,
    width: fixWidth(0.99),
    height: '430',
    singleSelect: true,
    loadMsg: '數據裝載中......',
    columns: [[
      { field:'interfaceInfoCode', title:'資金通道編碼', width:fixWidth(0.3), align:'center' },
      { field:'retreatBatchCode',  title:'資金退回批次號', width:fixWidth(0.2), editor:'text', align:'center' },
      { field:'total',             title:'總筆數', width:fixWidth(0.1), editor:'text', align:'center' },
      { field:'totalMoney',        title:'總金額', width:fixWidth(0.1), editor:'text', align:'center' },
      { field:'def2', title:'操作', width:fixWidth(0.3), editor:'text', align:'center',
        formatter:function(value, row, index){
          var e = '<a href="#" onclick="toDetail('+index+')">詳情</a> | ';
          var d = '<a href="#" onclick="auditBatch('+index+',0)">審核通過</a> | ';
          var f = '<a href="#" onclick="auditBatch('+index+',1)">審核拒絕</a> ';
          return e + d + f;
        }
      }
    ]],
    pagination: true,
    pageIndex: 1,
    pageSize: 10,
    pageList: [10, 15, 20]
  })
}

步驟三:後端接收參數並輸出 JSON

int currentPage = request.getParameter("pageIndex") == null ? 1 : Integer.parseInt(request.getParameter("pageIndex"));
// 每頁行數
int showCount = request.getParameter("pageSize") == null ? 10 : Integer.parseInt(request.getParameter("pageSize"));
// 查詢條件
String obj = request.getParameter("obj");
if (StringUtils.notBlank(obj)) {
  fundRetreatVoucher = JsonUtils.toObject(obj, FundRetreatVoucherParam.class);
}
out = response.getWriter();
List<FundRetreatVoucher> frvs = fundRetreatVoucherService.findAllFundRetreatVoucher(page, fundRetreatVoucher);
int total = fundRetreatVoucherService.findAllFundRetreatVoucher(getTotal(), fundRetreatVoucher).size();
JSONObject json = new JSONObject();
json.put("list", frvs);   // 這個 key 前端寫死要讀 list
json.put("size", total);
out.print(json);

兩個容易出錯的地方

key 名稱是前後端的契約。這裡用 list 與 size,若後端改了名字,前端 BingData 裡的 data.list 與 data.size 也要同步改,否則表格會一片空白。注意這跟 EasyUI 官方 demo 用的 rows/total 不同,這是自訂格式。

查總數不要撈全部資料再取 size。上面範例為了示範用了 .size(),正式環境請改成 SELECT COUNT(*),否則資料量一大就會有嚴重的效能問題。

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