博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ExtJS4.2 根据数据库记录构建树形菜单
阅读量:6913 次
发布时间:2019-06-27

本文共 2030 字,大约阅读时间需要 6 分钟。

  背景:最近用ExtJS4.2做一个系统,需要在前端展示资源菜单,为树形结构,该树形结构是从数据库动态加载的。

  ExtJS的树形结构大致有两种情况:

    1.静态树形结构,此处不多说,看API就能简单明白;

    2.动态加载,ExtJS的特性是根据父节点ID来查询子节点,从而动态更新树形菜单,这里有一个缺陷,或许是我孤陋寡闻不知道,那就是无法根据数据库节点信息自动构建成为一棵树,记得zTree插件就有这个功能。

  那么,我希望能够根据数据库树节点信息自动的构建成一棵树,就需要自己去写个小算法在后台拼接成ExtJS需要的数据结构。

  代码部分:

  1.节点pojo,必要属性有:节点ID(id)、父节点ID(parentId)、文本信息(text)、孩子(children),其他属性,比如节点url,顺序order等根据自己需要设置。

public class Resource {    private Integer id;    private String text;    private Integer parentId;    private Boolean expanded;    private List
children = new ArrayList
();   }

  2.根据查询出来的节点List集合拼装成为前端展示需要的结构,这里写了个静态方法。

public static final 
List
buildTree(List
nodes) { if(null == nodes || nodes.size() == 0) return null; Map
resources = new HashMap
(); List
result = new ArrayList
(); try { for(int i=0; i
e : resources.entrySet()) { T node = e.getValue(); Method getparentId = node.getClass().getMethod("getParentId"); Integer parentId = (Integer) getparentId.invoke(node); if(parentId == 0) { result.add(node); } else { T parent = resources.get(parentId); if( null != parent) { @SuppressWarnings("unchecked") List
children = (List
) parent.getClass().getMethod("getChildren").invoke(parent); children.add(node); } } } } catch (Exception e) { e.printStackTrace(); } return result; }

  3.数据库记录。

  

  4.ExtJS前端代码。

Ext.onReady(function() {    var store = Ext.create('Ext.data.TreeStore', {        proxy: {            type: 'ajax',            url: 'your url'        },        root: {            text: '系统菜单',            id: 0,            expanded: true        }    });    var treePanel = Ext.create('Ext.tree.Panel', {        title: '树形菜单',        width: 300,        height: 350,        margin: '50 0 0 500',        store: store,        rootVisible: false,        useArrows: true,        renderTo: Ext.getBody()    });});

  5.效果图。

  

  6.完毕。

转载于:https://www.cnblogs.com/dreamroute/p/4638442.html

你可能感兴趣的文章
getopt() getopt_long()函数手册[中文翻译]
查看>>
小程序开发文本空格的添加
查看>>
IO多路复用
查看>>
外设系统的内部控制单元WDT
查看>>
java后台接口SSM框架解决跨域问题
查看>>
JavaScript基础之算术运算符 、 前后增量/前后减量运算符 、比较运算符、逻辑运算符、 程序流程控制...
查看>>
LESS介绍及其与Sass的差异(转载自伯乐在线,原文链接:http://blog.jobbole.com/24671/)...
查看>>
java求10!的阶乘
查看>>
Swing小技巧总结
查看>>
Linux命令(23)grep命令的使用
查看>>
蓝桥杯第五届B组 李白打酒
查看>>
shell编程基础练习
查看>>
【图像】Matlab图像标定工具箱
查看>>
映射对象标识符
查看>>
20165330 2017-2018-2 《Java程序设计》第3周学习总结
查看>>
jquery中的闭包
查看>>
CALayer上绘图
查看>>
string
查看>>
sql 语句整理
查看>>
mouse click with ctypes.windll and win32api
查看>>