1. 下载jstree https://www.jstree.com
将style.min.css,jstree.min.js还有下面几个图片放到工程CSS文件夹里
2.html文件引入头文件
<link th:href="@{/asserts/css/style.min.css}" rel="stylesheet">
<script src="asserts/js/jstree.min.js"></script>
3.jstree使用json格式如下
$.jstree.defaults.core.data 配置选项,data里每行数据必须有id,parent两字段。jstree会自动构建这个层次关系,根结点需要设置parent属性为"#".
// Alternative format of the node (id & parent are required)
{
id : "string" // required
parent : "string" // required
text : "string" // node text
icon : "string" // string for custom
state : {
opened : boolean // is the node open
disabled : boolean // is the node disabled
selected : boolean // is the node selected
},
li_attr : {} // attributes for the generated LI node
a_attr : {} // attributes for the generated A node
}
<script>
$(function () {
$("#myJstree").jstree({ 'core' : {
'data' : [
{ "id" : "ajson1", "parent" : "#", "text" : "Simple root node" },
{ "id" : "ajson2", "parent" : "#", "text" : "Root node 2" },
{ "id" : "ajson3", "parent" : "ajson2", "text" : "Child 1" },
{ "id" : "ajson4", "parent" : "ajson2", "text" : "Child 2" },
]
} });
});
</script>
</head>
<body>
<div id="jstree_demo_div"></div>
</body>
4.项目中使用ajax返回json格式给jstree
(1)html文件加入script如下:
$(function () {
$("#myJstree").jstree({ 'core' : {
'data' : function (obj, callback) {
var jsonstr="[]";
var jsonarray = eval('('+jsonstr+')');
$.ajax({
type: "GET",
url:"/TmenuTree",
dataType:"json",
async: false,
success:function(result) {
var arrays= result.data;
alert("1");
for(var i=0 ; i<arrays.length; i++){
console.log(arrays[i])
var arr = {
"id":arrays[i].id,
"parent":arrays[i].parent,
"text":arrays[i].text
}
jsonarray.push(arr);
}
}
});
callback.call(this, jsonarray);
}
}
});
});
(2)数据库menu结构:
(3)menu类
public class Menu {
private Integer menuId;
private String id;
private String parent;
private String text;
private String href;
private Integer sequence;
private Integer isEnable;
private String permission;
(4)mapper和service
@Mapper
public interface MenuTreeMapper {
@Select("select * from t_menu")
public List<MenuTree> getAllTMenus();
}
@Service
public class MenuTreeService {
@Autowired
MenuTreeMapper menuTreeMapper;
public List<MenuTree> getAllTmenus()
{
List<MenuTree> menuList= menuTreeMapper.getAllTMenus();
return menuList;
}
}
(5)controller,将menu查询的结果放入到json里
@ResponseBody
@RequestMapping(value="TmenuTree")
public String menuTree(HttpServletResponse response) {
response.setContentType("text/json");
response.setCharacterEncoding("utf-8");
System.out.println("menuTree");
List<MenuTree> menuList= menuTreeService.getAllTmenus();
//转换为json数据
JSONObject result = new JSONObject();
result.put("data",menuList);
System.out.println(result.toJSONString());
return result.toJSONString();
}
效果如下: