使用 zTree 动态加载树形菜单

 

1. 框架:

     jquery-1.8.3.js

     jquery.ztree.core-3.5.js

     Spring-3.2.4

 

     js及css见附件

 

2. 加载的数据

    省市数据。

    思路:一进入页面,首先加载省一级信息,当点击省的时候,到后台查找该省下面的所有的市,然后加载到该省下。

 

3. 表(HW_DEPT)结构

 
使用 zTree 动态加载树形菜单
 

4. 查找省一级数据dao方法

public List<HwDept> findProvinceDept(String provinceId) throws Exception {

		StringBuffer sql = new StringBuffer(100);

		sql.append("SELECT * FROM HW_DEPT ");
		sql.append(" WHERE DEPT_LEVEL = '3' AND MANAGE_LEVEL = '3'");

		if (null != provinceId && !"".equals(provinceId.trim())) {
			sql.append(" AND DEPT_ID = '").append(provinceId).append("'");
		}

		sql.append(" ORDER BY DEPT_NAME ASC");

		return getJdbcTemplate().query(sql.toString(), new RowMapper<HwDept>() {

			@Override
			public HwDept mapRow(ResultSet rs, int rowNum) throws SQLException {

				HwDept dept = new HwDept();

				dept.setDeptId(rs.getString("DEPT_ID"));
				dept.setDeptName(rs.getString("DEPT_NAME"));
				dept.setDeptLevel(rs.getString("DEPT_LEVEL"));
				dept.setManageLevel(rs.getString("MANAGE_LEVEL"));
				dept.setParentId(rs.getString("PARENT_ID"));

				return dept;
			}
		});
	}

 

5. 查找省一级数据controller方法

@RequestMapping("/getProvinceTree")
	public void getProvinceTree(HttpServletResponse resp) {

		PrintWriter out = null;

		try {
			out = resp.getWriter();

			// 当前登录用户
			ShiroUser shiroUser = SubjectUtils.getPrincipal();
			User user = userService.findOne("loginName",
					shiroUser.getLoginName());

			// 查找省一级部门信息
			List<HwDept> depts = hwDeptService.findProvinceDept(user
					.getProvinceId());
			//
			// JSONArray json = JSONArray.fromObject(depts);

			// 将集合对象拼接成json字符串
			String json = buildProvinceJSON(depts);

			log.info("Province Tree json is:\r\n" + json);

			// 传到前台js
			out.write(json);

			// JSONArray outArray = hwDeptService.findProvinceDept();

			// out.write(json.toString());
			out.flush();

		} catch (IOException e) {
			log.error("Get Province Tree fail:" + e.getMessage(), e);
		} catch (Exception e) {
			log.error("Get Province Tree fail:" + e.getMessage(), e);
		} finally {
			if (null != out) {
				out.close();
			}
		}
	}

 

private String buildProvinceJSON(List<HwDept> list) throws Exception {

		StringBuffer json = new StringBuffer(1000);

		for (HwDept dept : list) {

			json.append("{");
			json.append("id:\"").append(dept.getDeptId()).append("\",");
			json.append("pId:").append("0").append(",");
			json.append("name:").append("\"").append(dept.getDeptName())
					.append("\"").append(",");
			json.append("isParent:").append("true").append(",");
			json.append("open:").append("false");
			json.append("}").append(",");
		}

		String s = json.toString();

		if (s.endsWith(",")) {
			// 去掉最后面的逗号
			s = s.substring(0, s.lastIndexOf(","));
		}

		StringBuffer buf = new StringBuffer("[");

		buf.append(s);

		buf.append("]");

		return buf.toString();
	}

 

6. jsp

<ul id="tree" class="ztree" style="width:260px; overflow:auto;"></ul>

 

7. js

<script type="text/javascript">
/* 树形菜单 */
var zTree;
var demoIframe;

var setting = {
	view: {
		dblClickExpand: false,
		showLine: true,
		selectedMulti: false
	},
	data: {
		simpleData: {
			enable:true,
			idKey: "id",
			pIdKey: "pId",
			rootPId: ""
		}
	},
	callback: {
		/*
		beforeClick: function(treeId, treeNode) {
			alert(treeNode);
			var zTree = $.fn.zTree.getZTreeObj("tree");
			if (treeNode.isParent) {
				alert(treeNode);
				zTree.expandNode(treeNode);
				return false;
			} else {
				demoIframe.attr("src",treeNode.file + ".html");
				return true;
			}
		},
		*/
		onClick: reLoadOpenURL,//节点被点击时调用的函数
		beforeExpand: zTreeBeforeExpand //用于捕获父节点展开之前的事件回调函数,并且根据返回值确定是否允许展开操作
	}
};
$(function(){
			
	var zNodes;
	var zTreeObj;
	
	$.ajax({
		url : "${ctx}/hw/dept/getProvinceTree",
		type : "POST",
		dataType: "text", // 字符串格式
		success : function (strReult) {
			// 将json字符串转成json对象
			zNodes = eval("(" + strReult + ")");
			
			zTreeObj = $.fn.zTree.init($("#tree"), setting, zNodes);
			
		}, error: function () {
			alert("获取省公司数据失败!");
		}
	});
});
</script>

 

结果如下:


使用 zTree 动态加载树形菜单
 

下面加载子节点,点击省前面的加号(+),到后台查找对应的市一级数据,然后加载显示。

8. 根据省份id查找对应的市级信息dao方法

public List<HwDept> findByPId(String parentId) throws Exception {

		String sql = "SELECT * FROM HW_DEPT WHERE PARENT_ID = ? ORDER BY DEPT_NAME ASC";

		return getJdbcTemplate().query(sql, new Object[] { parentId },
				new RowMapper<HwDept>() {

					@Override
					public HwDept mapRow(ResultSet rs, int rowNum)
							throws SQLException {

						HwDept dept = new HwDept();

						dept.setDeptId(rs.getString("DEPT_ID"));
						dept.setDeptName(rs.getString("DEPT_NAME"));
						dept.setDeptLevel(rs.getString("DEPT_LEVEL"));
						dept.setManageLevel(rs.getString("MANAGE_LEVEL"));
						dept.setParentId(rs.getString("PARENT_ID"));

						return dept;
					}
				});
	}

 

9. 根据省份id查找对应的市级信息controller方法

@RequestMapping("/getCityTree")
	public void getCityTree(HttpServletResponse resp,
			@RequestParam("parentId") String parentId) {

		log.info("Get City Tree, parentId=" + parentId);

		PrintWriter out = null;

		try {
			out = resp.getWriter();

			List<HwDept> depts = hwDeptService.findByPId(parentId);

			// 将集合对象拼接成json字符串
			String json = buildCityJSON(depts, parentId);

			log.info("City Tree json is:\r\n" + json);

			// 传到前台js
			out.write(json);

			out.flush();

		} catch (IOException e) {
			log.error("Get City Tree fail:" + e.getMessage(), e);
		} catch (Exception e) {
			log.error("Get City Tree fail:" + e.getMessage(), e);
		} finally {
			if (null != out) {
				out.close();
			}
		}
	}
private String buildCityJSON(List<HwDept> list, String parentId)
			throws Exception {

		StringBuffer buf = new StringBuffer(1000);

		for (HwDept dept : list) {

			buf.append("{");
			buf.append("id:\"").append(dept.getDeptId()).append("\",");
			buf.append("pId:").append("\"").append(parentId).append("\",");
			buf.append("name:").append("\"").append(dept.getDeptName())
					.append("\"").append(",");
			buf.append("isParent:").append("true").append(",");
			buf.append("open:").append("false");
			buf.append("}").append(",");
		}

		String s = buf.toString();

		if (s.endsWith(",")) {
			// 去掉最后面的逗号
			s = s.substring(0, s.lastIndexOf(","));
		}

		StringBuffer json = new StringBuffer(1000);

		json.append("[");

		json.append(s);

		json.append("]");

		return json.toString();
	}

  

10. 加载子节点js方法

// beforeExpand: 用于捕获父节点展开之前的事件回调函数,并且根据返回值确定是否允许展开操作
		function zTreeBeforeExpand(treeId, treeNode) {

			var zTree = $.fn.zTree.getZTreeObj(treeId);
			
			if (treeNode.isParent) {
				/*如果是父节点*/
				if(treeNode.open){
					/*父节点为展开状态,则折叠父节点*/
					zTree.expandNode(treeNode,false,true,true,false);
				} else {
					/*父节点为折叠状态,点击展开后加载子节点 */
					var parentId = treeNode.id;
					$.ajax({
						url : "${ctx}/hw/dept/getCityTree",
						type : "POST",
						dataType: "text", // 字符串格式
						data: {parentId : parentId},
						success : function (data1) {
							
				            // 将json字符串转成json对象
				            zNodes = eval("(" + data1 + ")");
				            
				            zTree.addNodes(treeNode, zNodes); 
							
						}, error: function () {
							alert("获取市公司数据失败!");
						}
					});
				}
			}
		}

 

11. 结果如下:


使用 zTree 动态加载树形菜单
 

你可能感兴趣的:(ztree)