Jquery的treeview插件实现树形结构

本文介绍了如何利用Jquery的treeview插件展示从数据库获取的树形结构数据。首先,根据KPI_CODE、KPI_NAME、PARENT_CODE和LVL_ID字段组织数据,然后分步加载数据:默认显示前两级目录,点击二级目录加载三级目录。最后通过调用java代码和treeview插件来呈现数据。

Jquery的treeview插件实现树形结构


最近由于功能需要,要将数据库中的数据取出来,展现的形式是树状结构。

表中的数据大致为:

KPI_CODE为唯一id,KPI_NAME为名字,PARENT_CODE为父id,LVL_ID为层级

要展现的形式为:

具体实现逻辑如下:

思路:将数据库的数据查询出来,按某种格式处理后返回给前台,前台用jQuery的treeview插件将数据展现为树状结构。

步骤:

1.默认加载前两级目录

2.点击第二级目录,继续加载第三级目录

3.调用插件处理数据

java代码:

import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.struts2.ServletActionContext;

public class FMTreeAction {
	private String id;//指标id
	private String parentId;//父id
	private String lvl;//等级
	private String calcObjType;//岗位id
	
	private DaoHelper daoHelper;
	
	public String execute(){
		return "success";
	}

	public String getSubFMObj(){
		//System.out.println("getSubFMObj...");
		System.out.println("***id:"+id+",parentId:"+parentId+",calcObjType:"+calcObjType+",lvl:"+lvl);
		int lvlId = Integer.parseInt(lvl)+1;
		this.lvl = String.valueOf(lvlId);
		System.out.println("***id:"+id+",parentId:"+parentId+",calcObjType:"+calcObjType+",newlvl:"+lvl);
		
		List subList = daoHelper.queryForList("ecthree.manParaInfo.initTree.getSubFMObj", this);
		//List resultList = new ArrayList();
		int subSize = subList.size();
		for (int i = 0; i < subSize; i++) {
			Map<String, Object> subMap = (Map<String, Object>) subList.get(i);
			valueChange(subMap);
			//打印输出
			//System.out.println("subMap--"+i+":");
			//BccUtils.printMap(subMap);
			
		}
		this.response(JSONArray.fromObject(subList).toString());
		return null;
	}
	//获取一级二级节点
	public String getFMObj(){
		//System.out.println(id);
		//获取一级目录
		List fatherList = daoHelper.queryForList("ecthree.manParaInfo.initTree.getOneFMObj", this);
		//System.out.println("fatherList.size()---"+fatherList.size());
		for(int k = 0; k < fatherList.size(); k++){
			Map<String, Object> fatherMap = (Map<String, Object>) fatherList.get(k);
			valueChange(fatherMap);
			//打印输出
			//System.out.println("fatherMap--"+k+":");
			//BccUtils.printMap(fatherMap);
			
			//根据一级目录id查询二级目录
			this.parentId = (String)fatherMap.get("KPI_CODE");
			System.out.println("parentId:"+parentId);
			List subList =daoHelper.queryForList("ecthree.manParaInfo.initTree.getTwoFMObj",this);
	 		int subSize = subList.size();
			for (int i = 0; i < subSize; i++) {
				Map<String, Object> subMap = (Map<String, Object>) subList.get(i);
				valueChange(subMap);
				//打印输出
				//System.out.println("subMap--"+i+":");
				//BccUtils.printMap(subMap);
			}
			fatherMap.put("ChildNodes", subList);
		}
		this.response(JSONArray.fromObject(fatherList).toString());
		return null;
	}
	private void valueChange(Map<String, Object> map) {
		map.put("id", map.get("KPI_CODE"));
		map.put("text", map.get("KPI_NAME"));
		map.put("calcObjType", map.get("CLAL_OBJ_TYPE"));
		map.put("lvl", map.get("LVL_ID"));
		map.put("parent_id", map.get("PARENT_CODE"));
		BigDecimal childNum = (BigDecimal) map.get("CHILDNUM");
		if (childNum == null || childNum.intValue() == 0) {
			map.put("hasChildren", false);
		} else {
			map.put("hasChildren", true);
		}
	}
	protected void response(String message){
		try {
			HttpServletResponse response =ServletActionContext.getResponse();
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			out.print(message);
			out.close();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
	}
	
	public DaoHelper getDaoHelper() {
		return daoHelper;
	}

	public void setDaoHelper(DaoHelper daoHelper) {
		this.daoHelper = daoHelper;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getParentId() {
		return parentId;
	}

	public void setParentId(String parentId) {
		this.parentId = parentId;
	}

	public String getCalcObjType() {
		return calcObjType;
	}

	public void setCalcObjType(String calcObjType) {
		this.calcObjType = calcObjType;
	}

	public String getLvl() {
		return lvl;
	}

	public void setLvl(String lvl) {
		this.lvl = lvl;
	}

	
	
}

jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="b" uri="/bonc-tags" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
	String contextPath = request.getContextPath();
%>
<html>
<head>
	<s:head />
	<s:head template="head_ext.ftl" />
	<script>
		var contextPath="<%=contextPath%>";
	</script>
	<link href="<%=contextPath%>/resources/boncbcs/base/css/base.css" rel="stylesheet" type="text/css" />
	<link href="<%=contextPath%>/resources/boncbcs/tho/jquery/jqueryui/themes/ui-lightness/jquery.ui.all.css" rel="stylesheet" type="text/css" />
	<link href='<b:url value="/resources/boncbcs/bcc/base/css/base.css"/>' rel="stylesheet" type="text/css"/>
	<link href='<b:url value="/resources/boncbcs/bcc/org/css/01-base.css"/>' rel="stylesheet" type="text/css" />
	<link href="<%=contextPath%>/resources/boncbcs/tho/jquery/tree/css/tree.css" rel="stylesheet" type="text/css" />
 	<link href="<%=contextPath%>/resources/boncbcs/bcc/org/css/tree.css" rel="stylesheet" type="text/css" >
    <link href="<%=contextPath%>/resources/boncbcs/tho/jquery/tree/css/page.css" rel="stylesheet" type="text/css" />
    <link href="<%=contextPath%>/resources/boncbcs/bcc/ptl/bccptl.css" rel="stylesheet" type="text/css" />
	<script src="<%=contextPath%>/resources/boncbcs/tho/jquery/jquery.min.js" type="text/javascript"></script>
	<script src="<%=contextPath%>/resources/boncbcs/tho/jquery/jquery.ui.custom.min.js" type="text/javascript"></script>
	<script src="<%=contextPath%>/resources/boncbcs/tho/jquery/jquery.validate.pack.js" type="text/javascript"></script>
	<script type="text/javascript" src="<%=contextPath%>/resources/boncbcs/tho/My97DatePicker/WdatePicker.js" defer="defer"></script>
	<script src="<%=contextPath%>/resources/boncbcs/bcc/base/js/showTips.js" type="text/javascript"></script>
	<script src="<%=contextPath%>/resources/boncbcs/tho/jquery/tree/jquery.tree.js" type="text/javascript"></script>
	<script src='<b:url value="/resources/boncbcs/tho/jquery/fileUpload/ajaxfileupload.js"/>' type="text/javascript"></script>
	<script src="<%=contextPath%>/resources/boncbcs/js/forbid.js" type="text/javascript"></script>
	<link href="<%=contextPath%>/resources/boncbcs/bcc/bonc_bt/css/bonc_new.css" rel="stylesheet" type="text/css" >	
	

	<script type="text/javascript">

	
		//点击框,展示树
		var orgFoucus=function(){
		
			//alert($("#calc_obj_type").val());
		
			initTree();
			
			var offset = $("#selectCalcObjType").offset();
			var _height = $("#selectCalcObjType").height()+5;
			$("#mainTree").css('left',offset.left);
			$("#mainTree").css('top',offset.top+_height);
			$("#mainTree").show();
		};
		//关闭
		var closeWin=function(){
			$("#tree1").html('');
			$("#mainTree").hide();
		};
		//清空
		function clearObjs(){
			$("#selectCalcObjType").val('');	
			$("#CALC_OBJ_TYPE").val('');
			$("#mainTree").hide();
		}
		//确定
		function confirmWin(){
					
			$("#mainTree").hide();
			var itemIds = '';
			var itemNms = '';
			var str = "";
			$('#tree1 li li img[src$="checkbox_1.gif"]').each(function(){
				var arr = this.id.substring(6, this.id.length-3);
				if(arr.length>6){
					itemNms += jQuery(this).parent().attr("title") + ',';		    	
		    	itemIds += arr + ',';	
				}					
		  });
		  $("#myTree").html("");
		  $("#myTree").html(itemIds+"<br/>"+itemNms);
		}
		//初始化树的前两级
		var initTree=function(){
				$.getJSON(contextPath+"/bcc/ecthree/MyTree/FMTree!getFMObj.action", loadFMTree);
		};
		//处理初始化的前两级目录,即将其展现
		function loadFMTree(loadDataAll){
			var calcObjType = $("#calcObjType").val();//获取岗位id
			//alert(calcObjType);
			var roots = new Array();//一级目录数组
			for(var i=0;i<loadDataAll.length;i++){
				var loadData = loadDataAll[i];
				var root = {"id":loadData.id, "text":loadData.text, complete:true, "isexpand":false,"hasChildren":loadData.hasChildren, ChildNodes:loadData.ChildNodes, "lvl":loadData.LVL};
				roots[i] = root;
			}
			
			//showcheck为true时,表示可以多选
			var o = {showcheck:true, url:contextPath+"/bcc/ecthree/MyTree/FMTree!getSubFMObj.action?calcObjType="+calcObjType, onnodeclick:function (item) {
				//$("#myTree").html("");
				//var str = "id:"+item.id+"--name:"+item.text;
				//$("#myTree").html(str);
				//$("#mainTree").hide();
			}};
			o.data = roots;
			o.path = contextPath;
			$("#tree1").treeview(o); 
		}
		
		
	</script>
 </head>
 <body style="overflow-y:auto;">
	<div class="appletBox" >
		<div class="appletTitleBar">
			<div class="appletTitle"><s:property value="pojo.CALC_OBJ_TYPE_DESC"/>薪酬因子配置</div>
			<div class="appletIcon">
			</div>
		</div>
	</div>

	<table class="table11" style="width: 100%;">
		<tr height="34px">
				<td align="left">岗位类型:
					<select id="calc_obj_type">
						<option value="A01030_01">岗位1</option>
						<option value="A01030_02">岗位2</option>
						<option value="A01030_03">岗位3</option>
						<option value="A01030_04">岗位4</option>
						<option value="A01030_05">岗位5</option>
						<option value="A01030_06">岗位6</option>
						<option value="A01030_07">岗位7</option>
					</select>
				</td>
		    <td align="left">负面清单:<s:textfield  id="selectCalcObjType"  onclick="orgFoucus()" /></td>
			</tr>		
	</table>
	
	<div id="mainTree" style="display:none;width:240px;height:306px;position: absolute;">
		<div style="width:231px;height:299px;" class="x-window-background"></div>
		<div style="width:230px;" class="x-window">
			<div class="x-panel-header" >
				<span style="margin-left: 0px;">岗位类型</span>
				<a style="margin-left: 40px"  href="#" onclick="confirmWin();">确定</a>
				<a style="margin-left: 10px" href="#" onclick="clearObjs();">清空</a>
				<a style="margin-left: 10px"  href="#" onclick="closeWin();">关闭</a>
			</div>
			<div style="width: 228px;height:270px;overflow: auto;" class="x-panel-body">
				<div id="tree1" align="left" style="padding-left:20px;" class="ztree">
				</div>
			</div>
		</div>
	</div>	


<div id="showFileUp" class="fileUpDiv"></div>

	<div id="myTree">123123</div>
 </body>
</html>

mapper:

	<!-- 查询子节点 -->
	<select id="getSubFMObj" resultClass="java.util.HashMap">
		select a.*, 
        (select count(1) from kpicode.fm_kpi_code b 
                where a.kpi_code = b.parent_code 
        ) as childNum
    from  kpicode.fm_kpi_code a 
    where parent_code = #id# and lvl_id = #lvl# 
    order by kpi_code
    
	</select>
	
	<!-- 一级目录 -->
	<select id="getOneFMObj" resultClass="java.util.HashMap">
		select a.*, 
        (select count(1) from kpicode.fm_kpi_code b where a.kpi_code = b.parent_code) as childNum
    from  kpicode.fm_kpi_code a where a.lvl_id='1' and calc_obj_type is null order by kpi_code
	</select>
	<!-- 二级目录 -->
	<select id="getTwoFMObj" resultClass="java.util.HashMap">
		select *
   		from (select a.*,
           		(select count(1)
                from kpicode.fm_kpi_code b
                   where a.kpi_code = b.parent_code) as childNum
         		from kpicode.fm_kpi_code a
           		where  a.parent_code = #parentId#
     order by  a.kpi_code)
	</select>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值