最终效果:
点击非叶子节点时,向后台发送请求,获取下级菜单
前台代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
<%@ 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层:
1
2
3
4
5
6
7
8
9
10
11
|
@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层如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@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);
}
}
|
数据库结构如下: