Extjs4操作TreeStore处理proxyAjax获取的数据
最近在搞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;
- }