jQuery zTree v3.5 实例3 异步树

最终效果:

点击非叶子节点时,向后台发送请求,获取下级菜单

前台代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript" src="<%=basePath %>/js/jquery-1.8.1.js"></script>
	<script type="text/javascript" src="<%=basePath %>/js/jquery.ztree.all-3.5.min.js"></script>
	<link href="<%=basePath %>/css/zTreeStyle.css" rel="stylesheet" type="text/css"/>
	<script type="text/javascript">
		var zTree;
		var setting = {
			async: {
				enable: true,
				url:"<%=basePath%>menu/getMenu.action",
				autoParam:["id=pid"]
			},
			callback:{
				beforeClick:function(treeId,treeNode){
					if(treeNode.isParent){
						zTree.expandNode(treeNode);
						return true;
					}
					return false;
				}
			}
		}; 
		
		$(function(){
			zTree = $.fn.zTree.init($("#tree"), setting);
		});
	</script>
<body>
	<ul id="tree" class="ztree"></ul>
</body>
</html>


后台代码(springMVC+mybatis)如下:

controller层:

@Controller
@RequestMapping("menu")
public class MenuController {
	@Autowired
	private MenuService menuService;
	@RequestMapping("/getMenu")
	@ResponseBody
	public List<Menu> getMenu(@RequestParam(defaultValue="0")int pid) throws Exception{
		return this.menuService.getMenu(pid);
	}
}


service层如下:

@Service
public class MenuService {
	@Autowired
	private MenuDao menuDao;
	public List<Menu> getMenu(int pid) throws Exception{
		if(pid == 0){
			List<Menu> list = new ArrayList<Menu>();
			Menu menu = this.menuDao.getRoot();
			list.add(menu);
			return list;
		}
		return this.menuDao.getNextNodes(pid);
	}
}


 

数据库结构如下:

          

原文地址:https://www.cnblogs.com/james1207/p/3270928.html