树是一个我们日常用的组件,Ext给我们提供了一个非常好用的树控件,下面让我们看看用Ext创建一颗树是多么容易的。
<script>
Ext.onReady(function(){
var tree = new Ext.tree.TreePanel({
el:'tree'
});
var root = new Ext.tree.TreeNode({text:'root'});
var node1 = new Ext.tree.TreeNode({text:'catalog'});
var node2 = new Ext.tree.TreeNode({text:'catalog1_leaf'});
var node3 = new Ext.tree.TreeNode({text:'root_leaf'});
node1.appendChild(node2);
root.appendChild(node1);
root.appendChild(node3);
tree.setRootNode(root);
tree.render();
root.expand();
//可以有两个参数
});
</script>
</head>
<body>
<div id="tree" style="height:800px;"></div>
</body>
</html>
通过文件生成Tree
Ext.onReady(function(){
var tree = new Ext.tree.TreePanel({
el: 'tree',
loader: new Ext.tree.TreeLoader({dataUrl: 'data.txt'})
});
var root = new Ext.tree.AsyncTreeNode({text:'root'});
tree.setRootNode(root);
tree.render();
root.expand();
});
data.txt
[
{text:'01',children:[
{text:'01-01',leaf:true},
{text:'01-02',children:[
{text:'01-02-01',leaf:true},
{text:'01-02-02',leaf:true}
]},
{text:'01-03',leaf:true}
]},
{text:'02',leaf:true}
]
ajax读取
Ext.onReady(function(){
var tree = new Ext.tree.TreePanel({
el: 'tree',
loader: new Ext.tree.TreeLoader({dataUrl: 'data.jsp'})
});
var root = new Ext.tree.AsyncTreeNode({
id: '0',
text:'root'
});
tree.setRootNode(root);
tree.render();
root.expand(false, false);
});
<%@ page contentType="text/html;charset=utf-8"%>
<%
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
// 对应的是正在展开的节点id
String node = request.getParameter("node");
System.out.println(node);
String content = "";
if ("0".equals(node)) {
content += "[{id:1,text:'节点阿一'},{id:2,text:'节点阿二'}]";
} else if ("1".equals(node)) {
content += "[{id:11,text:'节点阿一一',leaf:false},{id:12,text:'节点阿一二',leaf:true}]";
} else if ("2".equals(node)) {
content += "[{id:21,text:'节点阿二一',leaf:true},{id:22,text:'节点阿二二',leaf:true}]";
} else if ("11".equals(node)) {
content += "[{id:111,text:'节点阿一一一',leaf:true},{id:112,text:'节点阿一一二',leaf:true}]";
}
response.getWriter().print(content);
%>
注意:ajax默认使用utf-8编码格式,所以我们的jsp也要使用utf-8编码发送数据。