DIV CSS 佈局教程網

ExtJs GridPanel 動態加載數據的完整實例
編輯:JavaScript綜合知識     

GridPanel 的列模型與數據源往往不是寫死的,而是由後台返回、前端動態構建。這樣做的好處是同一個 grid 組件能適配不同的業務場景。本文用一個標簽模型管理的例子走一遍完整流程。

前端:工具欄與表格初始化

<script type='text/javascript'>
// 解析後台返回的最大排序號,回填到表單
function editEsOrder(options, success, response) {
  if (success) {
    var json = Ext.util.JSON.decode(response.responseText);
    Ext.getCmp('esorder').setValue(json.maxOrderId);
  }
}

var tagModelManager_toolBar = new Ext.Toolbar({
  items: [
    { id: 'tagModel_Save', text: '添加', iconCls: 'add', handler: tagModel_Save },
    '-',
    { id: 'tagModel_dropSelected', text: '刪除', iconCls: 'remove', handler: tagModel_dropSelected }
  ]
});

new Ext.grid.GridPanel({
  id: 'tagModelManager_tagModelGrid',
  autoScroll: true,
  store: new Ext.data.Store(),
  cm: new Ext.grid.ColumnModel([new Ext.grid.RowNumberer()]),
  sm: new Ext.grid.CheckboxSelectionModel(),
  renderTo: 'tagModelManager_tagModelDiv',
  width:  Ext.getCmp('TagModel_win').getSize().width  - 16,
  height: Ext.getCmp('TagModel_win').getSize().height - 35,
  hideHeaders: false,
  loadMask: { msg: '正在加載數據,請稍候....' },
  collapsible: true,
  collapsed: false,
  bbar: new Ext.PagingToolbar({
    id: 'tagModelManager_tagModelPagingBar',
    pageSize: getComboValue(),
    store: new Ext.data.Store(),
    displayInfo: true
  }),
  tbar: tagModelManager_toolBar
});

Ext.getCmp('tagModelManager_tagModelGrid').render();
Ext.getCmp('tagModelManager_tagModelGrid')
   .on('rowdblclick', tagModelSelectRowDblClickEvent);

// 雙擊行進入編輯
function tagModelSelectRowDblClickEvent(selectionModel, rowIndex, selectedRecord) {
  var selectedRows = Ext.getCmp('tagModelManager_tagModelGrid')
                       .getSelectionModel().getSelections();
  var row = selectedRows[0];
  tagModel_SaveOrEdit('edit', row);
}

function tagModel_Save() {
  tagModel_SaveOrEdit('save');
}

動態構建列模型與數據源

function tagModelList_search() {
  Ext.Ajax.request({
    url: 'editTagModel.html?method=getParams',
    callback: getSearchList
  });
}

function getSearchList(options, success, response) {
  if (success) {
    var json = Ext.util.JSON.decode(response.responseText);
    tagModelManager_tagModelGridTitle   = json.tagModelManager_tagModelGridTitle;
    var record                          = json.record;
    var tagModelManager_tagModelColumnModels = json.tagModelManager_tagModelColumnModels;

    // 拼出完整列模型:序號列 + 勾選列 + 動態列
    var cm = new Ext.grid.ColumnModel(
      Ext.util.JSON.decode("[" +
        "new Ext.grid.RowNumberer()," +
        "new Ext.grid.CheckboxSelectionModel()," +
        tagModelManager_tagModelColumnModels +
      "]")
    );
    cm.defaultSortable = true;

    var store = new Ext.data.Store({
      baseParams: {
        tagModelKeyword: Ext.getCmp('tagModelManager_search_button')
                           .el.dom.value.trim()
      },
      proxy: new Ext.data.HttpProxy({
        url: 'editTagModel.html?method=getTagModelDataList'
      }),
      reader: new Ext.data.JsonReader({
        totalProperty: 'resultSize',
        root: 'tagModelList'
      }, Ext.util.JSON.decode(record))
    });

    Ext.getCmp('tagModelManager_tagModelPagingBar').bind(store);
    store.load({ params: { start: 0, limit: getComboValue() } });

    Ext.getCmp('tagModelManager_tagModelGrid').setTitle(tagModelManager_tagModelGridTitle);
    Ext.getCmp('tagModelManager_tagModelGrid').reconfigure(store, cm);
    Ext.getCmp('tagModelManager_tagModelGrid').expand(false);
  }
}

// 不加關鍵字的普通查詢,邏輯同上
function tagModelList_all() {
  Ext.Ajax.request({ url: 'editTagModel.html?method=getParams', callback: getTagModel });
}

function getTagModel(options, success, response) {
  if (success) {
    var json = Ext.util.JSON.decode(response.responseText);
    tagModelManager_tagModelGridTitle   = json.tagModelManager_tagModelGridTitle;
    var record                          = json.record;
    var tagModelManager_tagModelColumnModels = json.tagModelManager_tagModelColumnModels;

    var cm = new Ext.grid.ColumnModel(
      Ext.util.JSON.decode("[" +
        "new Ext.grid.RowNumberer()," +
        "new Ext.grid.CheckboxSelectionModel()," +
        tagModelManager_tagModelColumnModels +
      "]")
    );
    cm.defaultSortable = true;

    var store = new Ext.data.Store({
      proxy: new Ext.data.HttpProxy({ url: 'editTagModel.html?method=getTagModelDataList' }),
      reader: new Ext.data.JsonReader({
        totalProperty: 'resultSize',
        root: 'tagModelList'
      }, Ext.util.JSON.decode(record))
    });

    Ext.getCmp('tagModelManager_tagModelPagingBar').bind(store);
    store.load({ params: { start: 0, limit: getComboValue() } });

    Ext.getCmp('tagModelManager_tagModelGrid').reconfigure(store, cm);
    Ext.getCmp('tagModelManager_tagModelGrid').expand(false);
  }
}

Ext.Ajax.request({ url: 'editTagModel.html?method=getParams', callback: getTagModel });
</script>

後端:返回結構定義與分頁數據

後端需要提供兩個接口。第一個返回列定義與字段元信息,供前端構建 ColumnModel 和 JsonReader:

public void getParams(ActionMapping mapping, ActionForm actionform,
                      HttpServletRequest request, HttpServletResponse response) {
  LinkedHashMap<String, String> tags = new LinkedHashMap<String, String>();
  tags.put("id", "id");
  tags.put("esidentifier", "字段");
  tags.put("estype", "類型");
  tags.put("esdescription", "描述");
  tags.put("esorder", "順序");
  tags.put("metadata", "元數據");
  tags.put("esisnull", "是否為必填項");
  tags.put("eslength", "字段長度");
  tags.put("esdotlength", "小數點位數");
  tags.put("esissystem", "是否為系統字段");

  JSONObject json = new JSONObject();
  json.put("record", getJsonRecord(tags));
  json.put("tagModelManager_tagModelColumnModels", getJsonColumnModel(tags));
  writeJson(response, json.toString());
}

第二個接口返回實際數據,並在服務端完成分頁截取:

public void getTagModelDataList(ActionMapping mapping, ActionForm actionform,
                                HttpServletRequest request, HttpServletResponse response) {
  ITagModelManager tagmgr = this.getPkgServer().getDriver()
                                .getOperateServer().getTagModelManager();
  List<HashMap<String, String>> models = new ArrayList<HashMap<String, String>>();

  String tagModelKeyword = request.getParameter("tagModelKeyword");
  List<EssTagModel> tagModels = tagmgr.getEssTagModels();

  int resultSize = 0;
  if (null != tagModels && !tagModels.isEmpty()) {
    resultSize = tagModels.size();

    // 按 start / limit 做分頁
    String start   = request.getParameter("start");
    String perPage = request.getParameter("limit");
    if (null != start && null != perPage) {
      int fromIdx = Integer.parseInt(start);
      int per     = Integer.parseInt(perPage);
      int toIdx   = fromIdx + per;
      if (toIdx > resultSize) toIdx = resultSize;
      tagModels = tagModels.subList(fromIdx, toIdx);
    }

    for (EssTagModel etm : tagModels) {
      HashMap<String, String> map = new HashMap<String, String>();
      map.put("id", Long.toString(etm.getId()));
      map.put("esidentifier", etm.getEsidentifier());
      map.put("estype", etm.getEstype());
      map.put("esdescription", etm.getEsdescription());
      map.put("esorder", Long.toString(etm.getEsorder()));
      map.put("metadata", etm.getMetadata());
      models.add(map);
    }
  }

  JSONObject json = new JSONObject();
  json.put("tagModelList", new JSONArray(models));
  json.put("resultSize", resultSize);
  writeJson(response, json.toString());
}

流程串講與改進建議

頁面初始化時先建立一個「空殼」grid(只有序號列),隨後異步請求 getParams 拿回列定義,用 reconfigure(store, cm) 一次性把新的列模型與數據源裝上去。數據請求由 PagingToolbar 觸發,後端按 start / limit 截取後返回,配合 totalProperty: 'resultSize' 讓分頁欄算出總頁數。

這套代碼能跑通,但按今天的標準看有幾處值得改進。

前後端重複代碼太多。getSearchList 與 getTagModel 幾乎完全相同,只差一個 baseParams。應抽成一個函數,用參數區分是否帶關鍵字。

用字符串拼接生成 JS 代碼。Ext.util.JSON.decode("[new Ext.grid.RowNumberer(),...]") 這種做法本質是 eval,既不安全也難調試。更好的方式是後台直接返回完整的列定義 JSON,前端用 Ext.create 逐項實例化,或者乾脆在前端寫死列結構——列定義隨請求變化的設計本身就值得商榷。

服務端內存分頁不可取。tagmgr.getEssTagModels() 把全量數據查出來再 subList,數據量一大就會有嚴重的性能與內存問題。應把 start / limit 下推到 SQL 的 LIMIT 子句。

關鍵字參數收了但沒用。tagModelKeyword 從 request 中取出後從未使用,說明查詢過濾並未真正生效。

Legacy 框架。ActionMapping、ActionForm 屬於 Struts 1 系列,早已停止維護。若仍在其上開發,建議把新功能放到 Spring MVC 或更新的技術棧中;ExtJs 3.x similarly 也已過時,新項目可考慮 Ext JS 現代工具包或完全不同的前端框架。

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