转载请注明出处:https://mp.csdn.net/postedit/88244560
树状图功能:最开始加载父级,在点击某个父节点时异步加载对应的子节点
在要求页面兼容ie8的情况下我选择的layui作为我的后台管理页面框架,但是layui对树状图的支持并不算太好,这里引入zTree作为补充。下面用到的一些js和css请到对应的官网下载首先看前端jsp的页面:
org.jsp:页面用了表格,引入了一个单独的树状图页面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<!--在ie8浏览器里面有些样式会乱,引用谷歌的一个插件-->
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>机构管理</title>
<link rel="stylesheet" href="../statics/layui/css/layui.css" media="all">
<script src="../statics/layui/layui.js"></script>
<style>
body{margin: 10px;}
.demo-carousel{height: 200px; line-height: 200px; text-align: center;}
</style>
</head>
<body>
<!-- 兼容ie8,加在body里面-->
<script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
<script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
<div class="layui-row">
<div class="layui-col-md3">
<%@include file="orgTree.jsp" %>
</div>
<div class="layui-col-md9">
<table class="layui-hide" id="demo" lay-filter="test"></table>
</div>
</div>
<script src="../statics/js/organization.js"></script>
</body>
</html>
organization.js:
layui.use(['laydate', 'laypage', 'layer', 'table', 'carousel', 'upload', 'element', 'slider'], function(){
var laydate = layui.laydate //日期
,laypage = layui.laypage //分页
,layer = layui.layer //弹层
,table = layui.table //表格
,carousel = layui.carousel //轮播
,upload = layui.upload //上传
,element = layui.element //元素操作
,slider = layui.slider //滑块
,$ = layui.jquery
//监听Tab切换
element.on('tab(demo)', function(data){
layer.tips('切换了 '+ data.index +':'+ this.innerHTML, this, {
tips: 1
});
});
//执行一个 table 实例
table.render({
elem: '#demo'
,height: 420
,url: '/mvc-demo/org/findorglist' //数据接口
,cellMinWidth: 80 //全局定义常规单元格的最小宽度,layui 2.2.1 新增
,title: '机构表'
,page: true //开启分页
//,toolbar: 'default' //开启工具栏,此处显示默认图标,可以自定义模板,详见文档
,totalRow: false //开启合计行
,cols: [[ //表头
{type: 'checkbox', fixed: 'left'}
,{field: 'id', title: 'ID', sort: true, fixed: 'left', totalRowText: '合计:'}
,{field: 'orgId', title: '机构号', }
,{field: 'orgName', title: '机构',sort: true}
,{field: 'regional', title: '所属地区', sort: true}
,{field: 'superior', title: '上级机构', sort: true, totalRow: true}
,{field: 'city', title: '城市'}
/* ,{field: 'sign', title: '待定', width: 200}
,{field: 'classify', title: '待定', width: 100}
,{field: 'wealth', title: '待定', width: 135, sort: true, totalRow: true} */
/* ,{fixed: 'right', width: 165, align:'center', toolbar: '#barDemo'}*/
]]
});
//监听头工具栏事件
table.on('toolbar(test)', function(obj){
var checkStatus = table.checkStatus(obj.config.id)
,data = checkStatus.data; //获取选中的数据
switch(obj.event){
case 'add':
layer.msg('添加');
var data = checkStatus.data;
// location.href = '../ui/people/addPeople.jsp';
layer.open({
type : 2,
title: "增加机构",
area: [ '600px', '500px'],
content : '../ui/addOrg.jsp',
shade : '0',
});
break;
case 'update':
if(data.length === 0){
layer.msg('请选择一行');
} else if(data.length > 1){
layer.msg('只能同时编辑一个');
} else {
layer.alert('编辑 [id]:'+ checkStatus.data[0].id);
layer.open({
type: 2,
title:"修改机构",
area: ['60%','80%'],
content: '../ui/modifyOrg.jsp',
shade : '0',
success: function(layero,index){
var idInput = $("#peopleId",layero.find("iframe")[0].contentWindow.cocument);
idInput.attr("value",id);
alert($("#peopleId").val());
},
});
}
break;
case 'delete':
if(data.length === 0){
layer.msg('请选择一行');
} else {
layer.msg('删除');
}
break;
};
});
//监听行工具事件
table.on('tool(test)', function(obj){ //注:tool 是工具条事件名,test 是 table 原始容器的属性 lay-filter="对应的值"
var data = obj.data //获得当前行数据
,layEvent = obj.event; //获得 lay-event 对应的值
if(layEvent === 'detail'){
layer.msg('查看操作');
} else if(layEvent === 'del'){
layer.confirm('真的删除行么', function(index){
obj.del(); //删除对应行(tr)的DOM结构
layer.close(index);
//向服务端发送删除指令
});
} else if(layEvent === 'edit'){
layer.msg('编辑操作');
}
});
});
orgTree.jsp:树状图页面
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<script type="text/javascript" src="../statics/zTree/js/jquery-1.4.4.min.js"></script>
<link rel="stylesheet" href="../statics/zTree/css/demo.css" type="text/css">
<link rel="stylesheet" href="../statics/zTree/css/zTreeStyle/zTreeStyle.css" type="text/css">
<script type="text/javascript" src="../statics/zTree/js/jquery.ztree.all.min.js"></script>
<div class="zTreeDemoBackground left">
<ul id="treeDemo" class="ztree"></ul>
</div>
<script type="text/javascript" src="../statics/js/orgTree.js"></script>
orgTree.js:树状图js
layui.use(['layer','tree'], function(){
tree = layui.tree //树状图
,layer = layui.layer //弹层
var setting = {
async: {
enable: true,
//初始化树状图的url
url:"/mvc-demo/org/tree",
//异步加载时需要自动提交父节点属性的参数
//autoParam:["id", "name=n", "level=lv"],
autoParam:["id"]
},
data: {
simpleData: {
enable: true,
idKey: "id",
pIdKey: "pId",
rootPId: 0
}
}
};
$(document).ready(function(){
$.fn.zTree.init($("#treeDemo"), setting);
});
});
后台控制器:表格的数据写死了,树状图根据传进来的id作为父类id查找集合
package com.mvc.demo.controller;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONArray;
import com.mvc.demo.pojo.Organization;
import com.mvc.demo.pojo.Tree;
import com.mvc.demo.service.ITreeService;
@Controller
@RequestMapping("/org")
public class OrgController {
@Autowired
private ITreeService treeService;
@RequestMapping(value = "/findorglist")
@ResponseBody
public Object findOrgs(@RequestParam int page, @RequestParam int limit) {
HashMap<String, Object> map = new HashMap<String, Object>();
List<Organization> orgList = new ArrayList<Organization>();
Organization org = null;
for (int i = 1; i <= 100; i++) {
org = new Organization();
org.setId(i);
org.setOrgId("orgID" + i);
org.setOrgName("机构名" + i);
org.setRegional("广东" + i);
org.setSuperior("上级机构" + i);
org.setCity("深圳" + i);
orgList.add(org);
}
List<Organization> pageList = new ArrayList<Organization>();
int index = ((page - 1) * limit);
int end = page * limit - 1;
for (int i = index; i <= end; i++) {
org = orgList.get(i);
pageList.add(org);
}
map.put("code", "0");
map.put("msg", "");
map.put("count", orgList.size());
map.put("data", pageList);
return map;
}
@RequestMapping( value = "/tree", produces = {"text/json;charset=UTF-8"})
@ResponseBody
public String getTree(Integer id) throws SQLException {
List<Tree> list=new ArrayList<Tree>();
list = treeService.findListByPid(id);
return JSONArray.toJSONString(list);
}
}
后台数据:isParent表示是否是父节点,设置为true页面会显示成文件夹
USE [test]
GO
/****** Object: Table [dbo].[tree] Script Date: 2019/3/6 11:27:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[tree](
[id] [int] NULL,
[pid] [int] NULL,
[NAME] [varchar](100) NULL,
[isParent] [varchar](100) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
INSERT [dbo].[tree] ([id], [pid], [NAME], [isParent]) VALUES (1, 0, N'清华大学', N'true')
INSERT [dbo].[tree] ([id], [pid], [NAME], [isParent]) VALUES (2, 1, N'软件工程学院', N'true')
INSERT [dbo].[tree] ([id], [pid], [NAME], [isParent]) VALUES (3, 1, N'国际贸易学院', N'true')
INSERT [dbo].[tree] ([id], [pid], [NAME], [isParent]) VALUES (4, 1, N'土木工程学院', N'false')
INSERT [dbo].[tree] ([id], [pid], [NAME], [isParent]) VALUES (5, 1, N'机电学院', N'false')
INSERT [dbo].[tree] ([id], [pid], [NAME], [isParent]) VALUES (6, 2, N'软件测试专业', N'true')
INSERT [dbo].[tree] ([id], [pid], [NAME], [isParent]) VALUES (7, 2, N'游戏开发专业', N'false')
INSERT [dbo].[tree] ([id], [pid], [NAME], [isParent]) VALUES (8, 6, N'C001班', N'false')
INSERT [dbo].[tree] ([id], [pid], [NAME], [isParent]) VALUES (9, 6, N'C002班', N'false')
INSERT [dbo].[tree] ([id], [pid], [NAME], [isParent]) VALUES (10, 3, N'对外贸易专业', N'true')
INSERT [dbo].[tree] ([id], [pid], [NAME], [isParent]) VALUES (11, 10, N'D001班', N'false')
INSERT [dbo].[tree] ([id], [pid], [NAME], [isParent]) VALUES (12, 10, N'D002班', N'false')