JSON数据生成树——(四)
1.页面中准备树的div
<div class="user_left_tree_info"> <div class="user_left_tree_info_title">部门</div> <div class="hr"></div> <div class="ztree" id="treeDemo"></div> </div>
2.页面加载时候请求树:
searchUnitTree();
/** * 请求树信息 */ function searchUnitTree(){ $.ajax({ type : "post", target : "#treeDemo", dataType : "json", url : "searchTreeAction2.action", success : getTree }); } /** * 生成树 */ function getTree(treeList2){ var treeList3 = eval("(" + treeList2 + ")"); var setting = { data : { simpleData : { enable : true, idKey: "unitId", pIdKey: "upUnitId", rootPId : "10", }, key : { name : "unitName", } }, callback : { onClick : onClick } }; var zNodes = treeList3; //添加 树节点的 点击事件; var log, className = "dark"; function onClick(event, treeId, treeNode, clickFlag) { clickOnTree(event, treeId, treeNode, clickFlag); } $.fn.zTree.init($("#treeDemo"), setting, zNodes); var treeObj = $.fn.zTree.getZTreeObj("treeDemo"); treeObj.expandAll(true); } /** * 点击树节点的同时,将该部门信息对应的部门编号,部门名称,上级部门编号,上级部门名称保存下来 */ function clickOnTree(event, treeId, treeNode, clickFlag){ //得到该节点的部门编号和部门名字 document.getElementById("bt_unitId").value = treeNode.unitId; document.getElementById("bt_unitName").value = treeNode.unitName; /*alert(treeNode.unitId); alert(treeNode.unitName);*/ if (treeNode.unitId == "10") { //如果本节点是根节点,那么就不能执行更新和删除操作 $("#unit_change,#unit_delete").attr("disabled","disabled"); } else { //如果本节点不是根节点,就可以执行更新和删除操作 $("#unit_change,#unit_delete").removeAttr("disabled"); //父节点 var fatherNode=treeNode.getParentNode(); /*alert(fatherNode.unitId); alert(fatherNode.unitName);*/ //得到父节点的部门编号和部门名称 document.getElementById("bt_upUnitId").value = fatherNode.unitId; document.getElementById("bt_upUnitName").value = fatherNode.unitName; } searchUnit(); } /** * 点击一下树节点表格输出下级节点的部门信息 */ function searchUnit() { $.ajax({ type : "post", dataType : "json", url : "searchUnitByUpId.action", data : { upUnitId : $("#bt_unitId").val(), }, success : showTable }); }
3.后台传JSON串
public String searchTree(){ try { this.treeList =unitService.getUnitTree2(); } catch (SQLException e) { e.printStackTrace(); } JSONArray jsonArray = JSONArray.fromObject(treeList); this.treeList2 = jsonArray.toString(); return SUCCESS; }
结果:
[{"upUnitId":"","unitName":"中心","unitId":"10"},{"upUnitId":"10","unitName":"人才","unitId":"10001"},{"upUnitId":"10","unitName":"项部","unitId":"10002"},{"upUnitId":"10","unitName":"成果","unitId":"10003"},{"upUnitId":"10","unitName":"SS","unitId":"10009"}]
【当你用心写完每一篇博客之后,你会发现它比你用代码实现功能更有成就感!】