最近在搞extjs4 TreeStore时有一个需求 就是要处理一下后台传过来的json数据然后再显示,看api也没有找到解决办法 ,最后看源码在Ext.data.proxy.Server 看到这么一个方法


[javascript] view plaincopy
  1. extractResponseData: function(response) {  
  2.      return response;  
  3. },  
然后我再 proxy 中重写了这个方法

大家都喜欢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;
}


相关文章:

  • 2022-02-04
  • 2021-12-12
  • 2022-12-23
  • 2022-12-23
  • 2021-09-14
  • 2021-04-18
  • 2022-12-23
  • 2021-11-12
猜你喜欢
  • 2021-09-21
  • 2022-12-23
  • 2022-12-23
  • 2021-08-18
  • 2021-05-16
  • 2022-12-23
相关资源
相似解决方案