---
title: "Ztree异步数据库交互实例"
author: "wktong"
date: "2012-07-26T16:17:48Z"
tags: ["ztree", "动态", "实例", "异步", "数据库"]
categories: ["Web前端"]
slug: "ztree"
draft: false
lastmod: "2012-07-28T16:51:33Z"
id: 1607654
url: "https://wktong.iteye.com/blog/1607654"
---

首先提供Ztree官方网站[http://www.ztree.me](http://www.ztree.me/v3/main.php#_zTreeInfo)。

Ztree是一个使用jQuery实现的JSP页面的各种功能树，本文介绍一个异步获取数据到下拉树的实现方式。

 

1、首先看数据库中的数据：

其中CLASSCODE，TRADECODE，CLASSLEVEL与Ztree的实现无关。

CLASSID：每个树节点自己的ID

CLASSNAME：顾名思义

TERMINATED：末端代号，用以判断是否为叶子节点（末节点）

PARENT：该节点的父节点ID  
![](http://dl.iteye.com/upload/attachment/0071/3544/6edb7f6b-c8b3-3368-84a2-36007a5a417e.png)

 

2、SQL：

工程使用的是oracle+ibatis，其查询语句如下。

（1）resultClass="hashmap"是指以hashmap类型返回查询结果

（2）isNotEmpty和isEmpty是ibatis的东西，顾名思义，满足哪个条件，就执行哪条语句。

【&lt;span style="white-space: pre;"&gt;    &lt;/span&gt;】下面这条语句莫名其妙多出来的，编辑不掉，当其不存在即可。

```
<select id="etpTradeZTree" resultClass="hashmap">
	select t.className as "name",
		  t.classId as "id" ,
		  t.parent as "pId",
		  t.terminated as "leaf"
	  from t_com_trade t
	where 1 = 1
	<isNotEmpty property="parent">
		and t.parent = #parent#
	</isNotEmpty>
	<isEmpty property="parent">
		and t.parent is null
	</isEmpty>
</select>
```

 

3、后台JAVA实现：

（1）ServiceImpl查出来的结果，放入一个List：

queryForList是ibatis提供的方法，获取数据库数据后，返回一个List类型的结果集。

```
public List ztreeEtpTrade(Long parent) {
	List list = treeDao.queryForList("common-selector.etpTradeZTree", "parent", parent);
	return list;
}
```

 

（2）在Action中，得到上面那个List，封装成Ztree需要的json格式后，再由action传到前台JSP。

每一次前台的点击，都会执行一次action获取数据，即实现了异步读取数据。

其中需要注意的是，我们调用SQL取数据的时候，需要给其一个参数parent，用以判断是否为父节点（根节点）。

$LongNull是封装在框架中的，其实就是request。

 

```
public void ztreeEtpTrade(){
	Long parent = $LongNull("id");//从前台传过来的，用来判断父节点
	if(parent!=null && parent == 0){
		parent = null;
	}
	List treeTrade = this.getCommonSelectorService().ztreeEtpTrade(parent);
	String json = JsonUtil.getJson(treeTrade);//变量json传给前台
	super.renderJson(json);
}
```

 

4、前台JSP：

&lt;script/&gt;标签内：可参考Ztree官方API查看各个属性的作用：[http://www.ztree.me/v3/api.php](http://www.ztree.me/v3/api.php)

（1）下面的代码，都是按照Ztree官方实例的结构来写的，我也只是明白了90%左右，主要还是settingTrade里面的配置。

```
var treeTrade;
var settingTrade = {
	data: {
		simpleData: {
			enable : true,
			idKey : "id",
		 	pIdKey : "pId"
		}
	},
	async: {
		enable: true,
		url:"${base}/common/selector/ztreeEtpTrade.action",
		autoParam:["id"],
		dataFilter: filter
	},
	callback: {
		onClick: onClickTrade
	}
};
function Node(id, pId, name, isParent){
	this.id = id;  
	this.pId = pId;  
	this.name = name;
	this.isParent = isParent;
};
function filter(treeId, parentNode, childNodes) {
	var filterNodes = new Array()
	if (!childNodes) return null;
	var isParent;
	for (var i=0, l=childNodes.length; i<l; i++) {
		childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
		if(childNodes[i].leaf==0){
			isParent = true;
			filterNodes.push(new Node(childNodes[i].id, childNodes[i].pId, childNodes[i].name, isParent));
		}else{
			isParent = false;
			filterNodes.push(new Node(childNodes[i].id, childNodes[i].pId, childNodes[i].name, isParent));
		}
	}
	return filterNodes;
};
function onClickTrade(e, treeId, treeNode) {
	var zTree = $.fn.zTree.getZTreeObj("treeTrade"),
	nodes = zTree.getSelectedNodes(),
	tradeName = "";
	tradeId = "";
	nodes.sort(function compare(a,b){return a.id-b.id;});
	for (var i=0; i<nodes.length; i++) {
		tradeId += nodes[i].id + ",";
		tradeName += nodes[i].name + ",";
	}
	if (tradeId.length > 0 ) tradeId = tradeId.substring(0, tradeId.length-1);
	if (tradeName.length > 0 ) tradeName = tradeName.substring(0, tradeName.length-1);
	var tradeIdObj = $("#tradeId");
	var tradeNameObj = $("#tradeName");
	tradeIdObj.attr("value", tradeId);
	tradeNameObj.attr("value", tradeName);
};
function showMenuTrade() {
	var treeNodes = new Array();
	var tradeObj = $("#tradeName");
	var tradeOffset = $("#tradeName").offset();
	$("#tradeContent").css({
		left:0/*tradeOffset.left + "px"*/,
		top:/*tradeOffset.top + */tradeObj.outerHeight() + "px"}).slideDown("fast");
	$("body").bind("mousedown", onBodyDownTrade);
	$.ajax({
		url : "${base}/common/selector/ztreeEtpTrade.action",
		type : "post",
		async : true,
		dataType: "json",
		success : function(data){
			var isParent;
			$.each(data, function(i, item){
				if(item.leaf==0){
		            		isParent = true;
		            	}else{
		            	<input type="hidden" name="etp.tradeId" id="tradeId" readonly="readonly"/>
 isParent = false;
		            	};
		            	treeNodes.push(new Node(item.id, item.pId, item.name, isParent));
		            	$.fn.zTree.init($("#treeTrade"), settingTrade, treeNodes);
			});
                }
	});
};
function hideMenuTrade() {
	$("#tradeContent").fadeOut("fast");
	$("body").unbind("mousedown", onBodyDownTrade);
}；
function onBodyDownTrade(event) {
	if (!(event.target.id == "menuBtn" || event.target.id == "tradeContent" || $(event.target).parents("#tradeContent").length>0)) {
		hideMenuTrade();
	}
};
```

 

 JSP的HTML：

 

```
<input type="text" name="etp.tradeName" id="tradeName" readonly="readonly"/>
<div class="zTreeDemoBackground left">
	<ul class="list">
		<li id="tradeContent" class="menuContent" style="position:absolute;left:0;top:-10px;z-index:800;background:#fff;border-left:1px solid #aaa;border-right:1px solid #aaa;border-bottom:1px solid #aaa;display:none;">
			<ul id="treeTrade" class="ztree" style="width:164px;"></ul>
 		</li>
	</ul>
</div>
```

```
<input type="button" name="tradeBtn" value="选&nbsp;&nbsp;择" id="tradeBtn" onclick="showMenuTrade(); return false;"/>
```

 

5、操作示例

（1）点击“选择”按钮，效果图如下：

![](http://dl.iteye.com/upload/attachment/0071/3572/a130df4b-d5e9-32e7-bc25-bfb4512d57e4.png)  
 后台action的过程：

会给parent传一个null值，执行SQL取数据，当传到action，数据如下（参照action代码）。

treeTrade的值：\[{id=1, pId=null, name=生产企业, leaf=0}, {id=2, pId=null, name=流通企业, leaf=0}]

json的值：\[{"id":1,"pId":null,"name":"生产企业","leaf":0},{"id":2,"pId":null,"name":"流通企业","leaf":0}]

 

（2）点击“生产企业”旁的加号，加载其孩子。

![](http://dl.iteye.com/upload/attachment/0071/3582/fa328435-1eb8-30f2-9bea-1602b14ce52f.png)

后台action的过程：

此次给parent传的值是1（“生产企业”的CLASSID）。

treeTrade的值：\[{id=3, pId=1, name=药品生产企业, leaf=1}, {id=7, pId=1, name=保健品生产企业, leaf=1}]

json的值：\[{"id":3,"pId":1,"name":"药品生产企业","leaf":1},{"id":7,"pId":1,"name":"保健品生产企业","leaf":1}]

 

所有代码都在上面了，不可能每行代码都解析清楚，我也是新人，多多指导交流。

1、先明白数据库的数据结构。

2、要想自己掌握的话，还是要靠自己一行一行代码去Google、百度，API。

3、除了Iteye，ztree在百度贴吧也有阵营，也可以去瞧瞧。[http://tieba.baidu.com/f?kw=ztree](http://tieba.baidu.com/f?kw=ztree)

4、推荐一篇文章：[这些年我们爱犯的弱智错误（菜鸟必看）](http://ztreeapi.iteye.com/blog/1423986)