ztree的异步加载

异步加载ZTree实现

异步加载:是指在数据量大的情况下,默认只加载根节点,当点击这个节点的时候才去加载这个节点下的子节点,不会一下子全部加载出数据,提高了查询数据的效率。

1.先引入ztree插件到静态文件目录下,包含js和css





2.建一个节点的实体类

public class TreeNode {
	 private String id;  
	    private String pId;  
	    private String name;  
	    private Boolean isParent;  
	    private Boolean hasChild;  
	    private String level;
	    public String getLevel() {
			return level;
		}
		public void setLevel(String level) {
			this.level = level;
		}
		public String getId() {  
	        return id;  
	    }  
	    public void setId(String id) {  
	        this.id = id;  
	    }  
	    public String getpId() {  
	        return pId;  
	    }  
	    public void setpId(String pId) {  
	        this.pId = pId;  
	    }  
	    public String getName() {  
	        return name;  
	    }  
	    public void setName(String name) {  
	        this.name = name;  
	    }  
	    public Boolean getIsParent() {  
	        return isParent;  
	    }  
	    public void setIsParent(Boolean isParent) {  
	        this.isParent = isParent;  
	    }  
	    public Boolean getHasChild() {  
	        return hasChild;  
	    }  
	    public void setHasChild(Boolean hasChild) {  
	        this.hasChild = hasChild;  
	    }    
	    
	  public TreeNode(String id, String pId,  
	    String name,  
	    Boolean isParent, 
	     Boolean hasChild,String level) {
			super();
			this.id = id;
			this.pId = pId;
			this.name = name;
			this.isParent = isParent;
			this.hasChild = hasChild;
			this.level=level;
		}
}

3.相关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 PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
 <HEAD>
  <TITLE> ZTREE DEMO </TITLE>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <link rel="stylesheet" href="<%=basePath %>/static/css/zTreeStyle/zTreeStyle.css" type="text/css">
  <script type="text/javascript" src="<%=basePath %>/static/js/jquery-1.4.4.min.js"></script>
  <script type="text/javascript" src="<%=basePath %>/static/js/jquery.ztree.core-3.1.js"></script>


  <script type="text/javascript">
		$(document).ready(function(){  
		    initMyZtree();  
		});  
		  
		var zNodes="";  
		var setting = {  
		    view: {  
		        selectedMulti: false,  
		        fontCss: setFontCss  
		    },  
		    async: {  
		        enable: true,  
		        url:"getZtree.do",  
		        autoParam:["id"]  
		    },  
		    callback: {  
		        beforeClick: beforeClickZtree  
		    }  
		};  
		  
		function initMyZtree(){  
		    $.ajax({                 
		        type: "POST",                 
		        dataType: "json",                 
		        url: 'getZtree.do',     
		        success: function(data) { 
		        	zNodes=data;  
		            $.fn.zTree.init($("#treeDemo"), setting, zNodes);  
		        }     
		    });    
		      
		}  
		  
		//单击事件  
		function beforeClickZtree(treeId, treeNode){  
		    alert(treeNode.id+","+treeNode.name);  
		}  
		  
		//设置字体 颜色
		function setFontCss(treeId, treeNode) {  
		    if(treeNode.level==0){  
		        return {'font-weight':'bold','color':'red'};  
		    }else if(treeNode.level==1){  
		        return {'font-weight':'bold','color':'green'};  
		    }else if(treeNode.level==2){  
		        return {'font-weight':'bold','color':'blue'};  
		    }else{  
		        return {};  
		    }  
		}; 
	</script>
</head>

<body>
 <ul id="treeDemo" class="ztree"></ul>  
</body>
</html>



4.controller处理:

数据是自己做的,没有查数据库

/**
     * ztree
     * @return
	 * @throws Exception 
     */
    @RequestMapping(value="getZtree.do")  
    @ResponseBody
    public String LoadTree(HttpServletResponse response,HttpServletRequest request) throws Exception
    {
    	
    	String id=request.getParameter("id");
    	System.out.println("*********"+id+"**********");  
        if("null".equals(id)||"".equals(id)||id==null){  
            id="0";  
        }  
        List<TreeNode> list=new ArrayList<TreeNode>(); //所有
        list.add(new TreeNode("CPIC","0","A",true,true,"0"));
    	list.add(new TreeNode("C01","CPIC","B",true,true,"1"));
    	list.add(new TreeNode("C02","CPIC","C",true,true,"1"));
    	list.add(new TreeNode("C001","C01","D",true,false,"2"));
    	list.add(new TreeNode("C002","C02","E",true,false,"2"));
        List<TreeNode> relist=new ArrayList<TreeNode>(); //需要的
        
        JSONArray jarray=new JSONArray();
        try {  
        	for (TreeNode t : list) {
    			if(t.getpId().equals(id)){
    				relist.add(t);
    			}
    		}
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        jarray.addAll(relist);  
        System.out.println(jarray.toString());  
        response.setCharacterEncoding("utf-8");  
        PrintWriter pw = null;  
        try {  
            pw = response.getWriter();  
            pw.write(jarray.toString());  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        pw.flush();  
        pw.close();  
        return null;  
    }  


5.预览:


大功告成,是不是很简单

下面附源码:https://download.youkuaiyun.com/download/yufeng005/10283997

### ZTree异步加载实现方法与示例 在ZTree中实现异步加载功能,需要配置`async`参数并确保后端接口能够正确返回数据。以下是详细的实现方法和代码示例: #### 1. 配置`async`参数 `async`参数用于定义异步加载的行为。关键属性包括: - `enable`: 是否启用异步加载[^3]。 - `url`: 指定后端接口地址,用于获取子节点数据[^3]。 - `autoParam`: 自动传递的参数,通常包含父节点的`id`。 - `dataFilter`: 数据过滤函数,用于处理后端返回的数据。 以下是一个完整的`setting`配置示例: ```javascript var setting = { view: { dblClickExpand: false, // 双击节点时不自动展开 selectedMulti: false // 禁用多选 }, data: { key: { name: "name" }, // 指定节点名称字段 simpleData: { enable: true // 启用简单数据模式 } }, async: { enable: true, // 启用异步加载 url: "/api/ztree/nodes", // 后端接口地址 autoParam: ["id"], // 自动传递父节点ID dataFilter: dataFilter // 数据过滤函数 }, check: { enable: true, // 启用复选框或单选框 chkStyle: "radio", // 使用单选框 radioType: "all" // 单选框作用范围为所有节点 } }; ``` #### 2. 初始化ZTree 通过`$.fn.zTree.init`方法初始化ZTree,并将配置和初始节点数据传递给它。 ```javascript // 初始化ZTree swjgtree = $.fn.zTree.init($("#treeContainer"), setting, initialNodes); // 展开第一个节点(如果存在) var nodes = swjgtree.getNodes(); if (nodes.length > 0) { swjgtree.expandNode(nodes[0], true, false); // 展开指定节点 } ``` #### 3. 数据过滤函数 `dataFilter`函数用于处理后端返回的数据,确保其格式符合ZTree的要求。 ```javascript function dataFilter(treeId, parentNode, childNodes) { if (!childNodes || !Array.isArray(childNodes)) { return []; } // 确保每个子节点都有isParent属性 childNodes.forEach(node => { if (node.children && node.children.length > 0) { node.isParent = true; // 子节点存在时设置为true } else { node.isParent = false; // 子节点不存在时设置为false } }); return childNodes; } ``` #### 4. 后端接口设计 后端接口应根据父节点ID返回对应的子节点数据。返回的数据格式需符合ZTree的要求,例如: ```json [ { "id": "1", "name": "节点1", "isParent": true }, { "id": "2", "name": "节点2", "isParent": false } ] ``` 后端接口示例(以Spring Boot为例): ```java @RestController @RequestMapping("/api/ztree") public class ZTreeController { @GetMapping("/nodes") public List<Map<String, Object>> getNodes(@RequestParam String id) { List<Map<String, Object>> nodes = new ArrayList<>(); // 根据父节点ID生成子节点数据 Map<String, Object> node1 = new HashMap<>(); node1.put("id", "1"); node1.put("name", "节点1"); node1.put("isParent", true); nodes.add(node1); Map<String, Object> node2 = new HashMap<>(); node2.put("id", "2"); node2.put("name", "节点2"); node2.put("isParent", false); nodes.add(node2); return nodes; } } ``` #### 注意事项 - `isParent`属性必须正确设置,否则可能导致无法正常显示子节点或出现异常行为[^1]。 - 如果某个节点没有子节点,应将其`isParent`设置为`false`,避免不必要的请求[^2]。 - 后端接口需支持根据父节点ID动态查询子节点数据
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值