標籤:treestore extjs4 extractresponsedata
最近在搞extjs4 TreeStore時有一個需求 就是要處理一下後台傳過來的json資料然後再顯示,看api也沒有找到解決辦法 ,最後看源碼在Ext.data.proxy.Server 看到這麼一個方法
[javascript] view plaincopy
- extractResponseData: function(response) {
- return response;
- },
然後我再 proxy 中重寫了這個方法
Ext.define("App.store.MenuStore",{extend:'Ext.data.TreeStore',model:'App.model.MenuModel',proxy:{type:'ajax',url:app.contextPath + '/base/syresource!doNotNeedSecurity_getMainMenu.action',reader:"json",extractResponseData: function(response) { var json = Ext.loadFilter(Ext.JSON.decode(response.responseText),{parentField : 'pid'}); Ext.each(json,function(record){ if(Ext.isEmpty(record.children)){ record.expanded = false; record.leaf = true; }else{ record.expanded = true; } }); response.responseText = Ext.JSON.encode(json); return response }},autoLoad: true});
大家都喜歡ztree的簡單資料結構(扁平pid結構資料集),而Extjs並沒有給我們提供,於是只有我們自己動手了。
標準的 JSON 資料需要巢狀表格示節點的父子內含項目關聯性
例如:var nodes = [{name: "父節點1", children: [{name: "子節點1"},{name: "子節點2"}]}];
簡單模式的 JSON 資料僅需要使用 id / pId 表示節點的父子內含項目關聯性
例如:
var nodes = [{id:1, pId:0, name: "父節點1"},{id:11, pId:1, name: "子節點1"},{id:12, pId:1, name: "子節點2"}];
這是我希望轉換的json資料
[ { "iconCls": "ext-icon-application_view_tile", "id": "xtgl", "target": "", "text": "系統管理", "url": "/welcome.jsp" }, { "iconCls": "ext-icon-newspaper_link", "id": "zygl", "pid": "xtgl", "target": "cmp", "text": "資源管理", "url": "App.view.ResourceView" }, { "iconCls": "ext-icon-tux", "id": "jsgl", "pid": "xtgl", "target": "cmp", "text": "角色管理", "url": "App.view.RoleView" }, { "iconCls": "ext-icon-group_link", "id": "jggl", "pid": "xtgl", "target": "cmp", "text": "機構管理", "url": "App.view.OrganizationView" }, { "iconCls": "ext-icon-user_suit", "id": "yhgl", "pid": "xtgl", "target": "cmp", "text": "使用者管理", "url": "App.view.UserView" },]
ExtJs只認識嵌套的json資料,這就需要我們進行轉換了,轉換的方法如下:
Ext.loadFilter= function(data, opt) {var idField, textField, parentField;if (opt.parentField) {idField = opt.idField || 'id';textField = opt.textField || 'text';parentField = opt.parentField || 'pid';var i, l, treeData = [], tmpMap = [];for (i = 0, l = data.length; i < l; i++) {tmpMap[data[i][idField]] = data[i];}for (i = 0, l = data.length; i < l; i++) {if (tmpMap[data[i][parentField]] && data[i][idField] != data[i][parentField]) {if (!tmpMap[data[i][parentField]]['children'])tmpMap[data[i][parentField]]['children'] = [];data[i]['text'] = data[i][textField];data[i]['leaf'] = true;//判斷為葉子節點tmpMap[data[i][parentField]]['children'].push(data[i]);} else {data[i]['text'] = data[i][textField];treeData.push(data[i]);}}return treeData;}return data;}
Extjs4 操作TreeStore 處理proxyAjax 擷取的資料