最近在搞extjs4 TreeStore時有一個需求 就是要處理一下后台傳過來的json數據然后再顯示,看api也沒有找到解決辦法 ,最后看源碼在Ext.data.proxy.Server 看到這么一個方法
- 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;
- }