ztree异步加载

以前一直困惑于树的动态加载,前几天用了treeview,但用于异步加载一直不太好用,弄得心力交瘁。而且treeview的api也没有。然后今天在csdn上看到有人提到ztree,我就去下了ztree的相关文件。不过学习也是需要过程,我差不多用了一个上午才搞定一个简单的异步加载。现在把相关的信息记录下来,既可以温故而知新,也可以帮助到其他人。

前台jsp页面:

<link rel="stylesheet" href="css/zTreeStyle.css" />
<script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>

<script src="js/jquery.ztree.core-3.5.js"></script>

<script>
var setting = {
  data: {

simpleData: {
enable: true,        //true / false 分别表示 使用 / 不使用 简单数据模式
idKey: "id",          //节点数据中保存唯一标识的属性名称
pIdKey: "parentId",      //节点数据中保存其父节点唯一标识的属性名称
rootPId: null          //用于修正根节点父节点数据,即 pIdKey 指定的属性值
}


}
,async: {
enable: true,         //设置 zTree 是否开启异步加载模式,默认值:false

url:"deptServlet?method=selectDept",     //Ajax 获取数据的 URL 地址

autoParam:["id"],               //异步加载时需要自动提交父节点属性的参数
dataFilter: filter                 //用于对 Ajax 返回数据进行预处理的函数
}
};
function filter(treeId, parentNode, childNodes) {
if (!childNodes) return null;
for (var i=0, l=childNodes.length; i<l; i++) {
childNodes[i].name = childNodes[i].name.replace('','');
}
return childNodes;
}

//json格式如下:
/* var zNodes =[
{ id:1, pId:0, name:"parentNode 1", open:true},
{ id:11, pId:1, name:"parentNode 11"},
{ id:111, pId:11, name:"leafNode 111"},
{ id:112, pId:11, name:"leafNode 112"},
{ id:113, pId:11, name:"leafNode 113"},
{ id:114, pId:11, name:"leafNode 114"},
{ id:12, pId:1, name:"parentNode 12"},
{ id:121, pId:12, name:"leafNode 121"},
{ id:122, pId:12, name:"leafNode 122"},
{ id:123, pId:12, name:"leafNode 123"},
{ id:13, pId:1, name:"parentNode 13", isParent:true},
{ id:2, pId:0, name:"parentNode 2", isParent:true}
]; */

$(document).ready(function(){
$.fn.zTree.init($("#treeDemo"), setting);
});

<div class="content_wrap">
<div class="zTreeDemoBackground left">
<ul id="treeDemo" class="ztree"></ul>
</div>
</div>

后台servlet:

public void selectDept(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String pId = request.getParameter("id");
if(pId==null) {
pId = "0";
}
JSONArray jsonArray = new JSONArray(); //创建JSONArray的实例
departmentList = deptDao.selectByUpperDep(pId); //传入一个upperDep,得到department类型的list
for (Department department : departmentList) {
JSONObject jsonObject = new JSONObject();
//将相应的属性表示成id,name,parentId,isParent,封装成json数据格式,前台可以直接使用
jsonObject.put("id",department.getDeptCode());
jsonObject.put("name", department.getDeptName());
jsonObject.put("parentId", department.getUpperDep());
jsonObject.put("isParent", true);
jsonArray.add(jsonObject); //将jsonObject添加进jsonArray里
}
response.setCharacterEncoding("utf-8"); //设置编码格式,解决页面显示乱码问题
PrintWriter out = response.getWriter();
out.write(jsonArray.toString()); //写入jsonArray
}

就这样就可以异步加载树了。

jsp页面显示如下:

原文地址:https://www.cnblogs.com/Aaronqcd/p/4028780.html