在Ext JS的Tree中的數據往往是從服務器端的動態程序中獲取的。
為了獲取數據,我們可以先編寫一個返回JSON的Servlet共前台的樹形組建訪問:
服務器端servlet代碼
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
public class TreeNodeServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//這裡的node是前台的AsyncTreeNode組建中設置的ID,見下面的JS程序
String treeNode = request.getParameter("node");
String json = "";
PrintWriter out = response.getWriter();
if("0".equals(treeNode)) {
json+="[{id:1,text:'0-1'},{id:2,text:'0-2'}]";
}
else if("1".equals(treeNode)) {
json+="[{id:11,text:'0-1-1',leaf:true},{id:12,text:'0-1-2',leaf:true}]";
}
else if("2".equals(treeNode)) {
json+="[{id:21,text:'0-2-1'},{id:22,text:'0-2-2',leaf:true}]";
}
else if("21".equals(treeNode)) {
json+="[{id:211,text:'0-2-1-1',leaf:true},{id:212,text:'0-2-1-2',leaf:true}]";
}
out.write(json);
}
}
現在就可以在前台的TreePanel組建的loader方法中訪問上面創建的servlet了,代碼如下:
客戶端顯示代碼
Ext.onReady(function(){
var tree = new Ext.tree.TreePanel({
//這裡的div-tree是在html中創建的一個對象的id值
el: 'div-tree',
//使用loader方法訪問TreeNodeServlet
loader: new Ext.tree.TreeLoader({dataUrl:'../TreeNodeServlet'})
});
var root = new Ext.tree.AsyncTreeNode({id:'0',text:'0'})
tree.setRootNode(root);
tree.render();
root.expand();
});