萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

ExtJS GridPanel 動態載入資料與動態欄位完整實作

前言

實務上常遇到「依查詢條件動態變更 Grid 欄位與資料」的需求。本文示範如何透過 Ajax 取得後端回傳的欄位定義與資料模型,動態重組 ColumnModel 與 Store,並搭配分頁工具列實現完整的動態 Grid 功能。

架構概覽

  1. 工具列:提供「新增」、「刪除」按鈕。
  2. 動態欄位:由後端回傳 JSON 定義,前端解析後重建 ColumnModel。
  3. 動態 Store:依查詢條件向後端請求資料,支援分頁。
  4. 雙重查詢模式:關鍵字搜尋(tagModelList_search)與全量載入(tagModelList_all)。
  5. 前端核心程式碼

    1. GridPanel 初始化

    new Ext.grid.GridPanel({
        id: 'tagModelManager_tagModelGrid',
        autoScroll: true,
        store: new Ext.data.Store(),           // 初始空 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
    });

    2. 取得後端欄位定義並重組 Grid

    function getSearchList(options, success, response) {
        if (success) {
            var tagModelManager_json = Ext.util.JSON.decode(response.responseText);
            var tagModelManager_tagModelGridTitle = tagModelManager_json.tagModelManager_tagModelGridTitle;
            var record = tagModelManager_json.record;                    // 欄位 Record 定義字串
            var tagModelManager_tagModelColumnModels = tagModelManager_json.tagModelManager_tagModelColumnModels; // 欄位定義字串
    
            // 動態建立 ColumnModel:RowNumberer + CheckboxSelectionModel + 後端欄位
            var tagModelManager_tagModelColumnModel = new Ext.grid.ColumnModel(
                Ext.util.JSON.decode('["new Ext.grid.RowNumberer()","new Ext.grid.CheckboxSelectionModel()",' + tagModelManager_tagModelColumnModels + ']')
            );
            tagModelManager_tagModelColumnModel.defaultSortable = true;
    
            // 動態建立 Store
            var strucutreModelManager_tagModelDataStore = 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))
            });
    
            // 綁定分頁工具列、載入資料、重組 Grid
            Ext.getCmp('tagModelManager_tagModelPagingBar').bind(strucutreModelManager_tagModelDataStore);
            strucutreModelManager_tagModelDataStore.load({ params: { start: 0, limit: getComboValue() } });
            Ext.getCmp('tagModelManager_tagModelGrid').setTitle(tagModelManager_tagModelGridTitle);
            Ext.getCmp('tagModelManager_tagModelGrid').reconfigure(strucutreModelManager_tagModelDataStore, tagModelManager_tagModelColumnModel);
            Ext.getCmp('tagModelManager_tagModelGrid').expand(false);
        }
    }

    3. 後端 Java 範例(Struts Action)

    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<>();
        String tagModelKeyword = request.getParameter("tagModelKeyword");
        List<EssTagModel> tagModels = tagmgr.getEssTagModels();
        int resultSize = 0;
    
        if (tagModels != null && !tagModels.isEmpty()) {
            resultSize = tagModels.size();
            String start = request.getParameter("start");
            String perPage = request.getParameter("limit");
            if (start != null && perPage != null) {
                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<>();
                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()));
                models.add(map);
            }
        }
        // 輸出 JSON:{ resultSize: 總筆數, tagModelList: [...] }
    }

    關鍵技術點總結

    技術點說明
    reconfigure()Grid 核心方法,同時替換 Store 與 ColumnModel,實現結構動態變更。
    動態 ColumnModel後端回傳欄位定義字串,前端用 Ext.util.JSON.decode 解析並注入 RowNumberer、CheckboxSelectionModel。
    動態 Record 定義後端回傳 record 字串(如 "[{name:'id'},{name:'name'}]"),前端解析為 JsonReader 欄位映射。
    手動分頁後端依 start/limit 參數截取 List,回傳 resultSize 供 PagingToolbar 計算總頁數。
    雙重查詢入口tagModelList_search 攜帶關鍵字,tagModelList_all 不帶關鍵字,共用同一組重組邏輯。

    最佳化建議

    • 後端改回傳標準 JSON 結構(fields、columns 陣列),避免字串拼接解析風險。
    • 前端統一使用 Ext.decode() 取代 Ext.util.JSON.decode()(ExtJS 4+)。
    • Store 建議改用 Ext.data.JsonStore 簡化配置。
    • 分頁邏輯移至資料庫層(LIMIT/OFFSET),避免記憶體載入全量資料再截取。
copyright © 萬盛學電腦網 all rights reserved