浅谈LigerUi Tree(树)
新到公司后,使用ligerui做了一个小练习,期间也遇到了一些问题,现在总结出来,以后方便查阅:
一.ligerui—tree(树)
ligerui可以非常简单的显示树,具体如下:
要使用ligerui框架,在官网上下载最新的jar包框架,解压之后,将Source –> lib整个文件夹引入到项目WebContent目录下
1) 在jsp页面中引入ligerui所需要的jar包(要根据要实现的不同的功能引入不同的jar包,如tree引入LigerTree的jar包,grid引入LigerGrid的jar包。。)
2) js代码:(ligertree有两种数据绑定的类型,(1):基于data, (2)基于url。 )
$("#tree1").ligerTree( { data:data });
或者: $(“#tree1”).ligerTree({ url: ‘tree.json’, ajaxType: ‘get’ });
3) tree中引用的data格式 或者后台返回的数据json的格式:
查看官方文档,必须是如下的格式:
也就是说,后台处理的数据返回之后要对数据进行拼凑,最后拼凑成这样的json格式返回前台。
按照以上的步骤,就可以显示完整的树了。
最终显示效果如下:
以下是我做的具体的小例子,(使用的是servlet+jsp,数据库设计,我是将父文件夹的id作为子文件夹的pid,具体见最下面的图),最后的结果是显示文件夹之间的层级:
// js代码:
//显示树$("#treeDatas").ligerTree({url : 'getAllDirs?' + $.param({typeid : '1',parentid : '0'}),checkbox : false,slide : false,isleaf : false,// onBeforeExpand : onBeforeExpand,onSelect :onSelect ,onClick : function(node) {if (node != null && node.data != null) {nodeid = node.data.id;//alert(nodeid);if (nodeid != -1 && node.data.typeid == -1) {gridManager.setOptions({parms : [ {name : 'organid',value : nodeid} ]});gridManager.loadData(true);}}}});
servlet:(查询数据库,将结果返回给前台,调用NodeUtil工具类中的treeDirList方法,将查到的list转换成前台data需要的数据格式返回前台)
private void findAllDir(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
req.setCharacterEncoding(“utf-8”);
resp.setContentType(“text/html;charset=UTF-8”);
PrintWriter printWriter = resp.getWriter();
List
String s = req.getParameter(“typeid”);
String s1 = req.getParameter(“parentid”);
int xx = Integer.parseInt(s1);
//System.out.println(s);
//System.out.println(s1);
JSONObject json = new JSONObject();String treeJson = "";int pid;NodeUtil nodeUtil = new NodeUtil();JSONArray jsonArray = new JSONArray();String jsonArray2 = null;for(int i=0;i<list.size();i++){jsonArray.add(list.get(i));}jsonArray2 = nodeUtil.treeDirList(jsonArray, xx).toString();String string = jsonArray2.replaceAll("dirName", "text");if (list != null && list.size() > 0) {for (Dir dir : list) {json.put("id", dir.getId());json.put("text", dir.getDirName());json.put("pid", dir.getPid());json.put("children", "[]");treeJson += json.toString() + ",";}}String string2 = "[{\"text\":\"upload\",\"id\":0,\"pid\":0,\"children\":"+string+"}]";printWriter.print(string2);printWriter.flush();printWriter.close();
}
工具类NodeUtil,用于通过递归算法,转换成前台需要的data格式,
public JSONArray treeDirList(JSONArray DirList, int parentId) {
JSONArray childDir = new JSONArray();
for (Object object : DirList) {
JSONObject jsonDir = JSONObject.fromObject(object);
int DirId = jsonDir.getInt(“id”);
int pid = jsonDir.getInt(“pid”);
if (parentId == pid) {
JSONArray c_node = treeDirList(DirList, DirId);
jsonDir.put(“children”, c_node);
childDir.add(jsonDir);
}
}
return childDir;
}
最后的运行效果:
数据库: