---
title: "Extjs4异步加载Tree"
author: "hm4123660"
date: "2014-03-31T12:49:07Z"
tags: ["Extjs4"]
categories: ["Web前端"]
slug: "extjs4-tree"
draft: false
lastmod: "2014-03-31T15:28:45Z"
id: 2038786
url: "https://longpo.iteye.com/blog/2038786"
---

**Extjs的jsp代码**：

&lt;%@ page language="java" contentType="text/html; charset=utf-8"

pageEncoding="utf-8"%&gt;

&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;

&lt;html&gt;

&lt;head&gt;

&lt;title&gt;TEST&lt;/title&gt;

&lt;!-- 在根目录下建立包里放js要加../ 来引用extjs的js和css--&gt;

&lt;link rel="stylesheet" type="text/css" href="../Ext4.2/resources/css/ext-all-neptune.css"&gt;

&lt;!-- 引入example.css，examples.js可使用Ext.example.msg('&lt;font color="#ff9900"&gt;警告&lt;/font&gt;',"不能重复作答！");输出--&gt;

&lt;link rel="stylesheet" type="text/css" href="../ExtJs/examples/shared/example.css" /&gt;

&lt;link rel="stylesheet" type="text/css" href="../icon.css"&gt;

  &lt;script type="text/javascript" src="../Ext4.2/bootstrap.js"&gt;&lt;/script&gt;

  &lt;script type="text/javascript" src="../ExtJs/examples/shared/examples.js"&gt;&lt;/script&gt;

  &lt;script type="text/javascript" src="../Ext4.2/locale/ext-lang-zh\_CN.js"&gt;&lt;/script&gt;

&lt;script type="text/javascript" src="tree.js"&gt;&lt;/script&gt;

&lt;/head&gt;

&lt;body&gt;

&lt;div  id="tree"&gt;&lt;/div&gt;

&lt;/body&gt;

&lt;/html&gt;

 

**ext 的js代码**：

Ext.onReady(function(){ 

var treestore = Ext.create('Ext.data.TreeStore', {

fields: [

    {name: 'id', type: 'string'},

    {name: 'node', type: 'string'},//为节点名称

    {name: 'content', type: 'string'},

    {name: 'leaf', type: 'bool'}   //这个一定要， 不然不能区分 是否是叶子

    ]，

root:{

        node:'广州',//根的名称

        id:'-100',//根的id

        expanded:false,

        leaf: false

       }

    });

 

treepanel = Ext.create('Ext.tree.Panel',{

id: 'treepanel',

region: 'center', 

flex:3,

 renderTo:'tree',//对应jsp的&lt;div  id="tree"&gt;&lt;/div&gt;

 title: '文档结构',

 store: treestore,

 rootVisible: true,// 显示根节点，false 不显示

 singleExpand: false,

 frame: true,

    tbar: ['-','-',

    {

        text:'全部折叠', 

        iconCls:'icon-collapse-all',

        handler:function(){

        treepanel.collapseAll();

    }

    }

    ],

 listeners:{

                  'beforeitemexpand':function(node,optd)// 节点展开监听

                  {

                  var ids=node.get('id');//获取节点ID

                  treestore.setProxy({

                                

                                    type: 'ajax',

                                    url:'getTreeData.action?ids='+ids,//传父ID到后台

                        reader:{

                                  type: 'json'

                                 // root:'children'//不写默认children

                               }

                  });

                  }

               },

               

               

    columns: [

        {

            xtype: 'treecolumn',//树列

            dataIndex: 'node',//节点名字

            text: '节点名字',

            flex: 1//比例显示

        },

        {

           text : '内容预览',

           xtype : 'gridcolumn',//表列

           dataIndex: 'content',//显示内容对应 store的fields里的content

           flex: 1

        }

    ]

});

   });

 

**建立一个树的实体：**

package excelTree;

 

import java.util.List;

 

public class TreeModel {

public String id;

public String node;

public String content;

public boolean leaf;

public List&lt;TreeModel&gt;children;//一次性加载用，异步不用。json 数据List用\[]包住，list内                                                          元素用{}。

public String getId() {

return id;

}

 

public void setId(String id) {

this.id = id;

}

 

public String getNode() {

return node;

}

 

public void setNode(String node) {

this.node = node;

}

 

public String getContent() {

return content;

}

 

public void setContent(String content) {

this.content = content;

}

 

public boolean isLeaf() {

return leaf;

}

 

public void setLeaf(boolean leaf) {

this.leaf = leaf;

}

public List&lt;TreeModel&gt; getChildren() {

return children;

}

public void setChildren(List&lt;TreeModel&gt; children) {

this.children = children;

}

}

 

**获取树的data的java方法**

package excelTree;

 

import java.util.ArrayList;

import java.util.List;

 

import javax.naming.NamingException;

 

import com.opensymphony.xwork2.ActionSupport;

 

import common.tools;

import excel.Excel;

import excel.ExcelBeanRemote;

 

public class TreeData extends ActionSupport {

 

/\**

 * 

 \*/

private static final long serialVersionUID = 1L;

final String pjName = new tools().moduleName();

public List&lt;TreeModel&gt;children;//记得get和set不然获取不到数据，js页面root没设置， 默                                                             认children

public String ids;//get和set得到 前台传来的 父ID

 

public List&lt;TreeModel&gt; getChildren() {

return children;

}

 

public void setChildren(List&lt;TreeModel&gt; children) {

this.children = children;

}

 

public String getIds() {

return ids;

}

 

public void setIds(String ids) {

this.ids = ids;

}

 

public ExcelBeanRemote remote(){

ExcelBeanRemote remote = null;

try {

remote = (ExcelBeanRemote) new tools().getContext().lookup(pjName+"ExcelBean!excel.ExcelBeanRemote");

} catch (NamingException e) {

e.printStackTrace();

}

return remote;

}

public String GetTreenode()

{

children=new ArrayList&lt;TreeModel&gt;();//实例化 List,这步记得加

List&lt;Excel&gt;excel=new ArrayList&lt;Excel&gt;();

excel=remote().getExcelParts(Integer.parseInt(ids));//根据父ID到 数据库获取其 下的节点

for(int i=0;i&lt;excel.size();i++)//放进List 的-children获取数据

{

TreeModel ok=new TreeModel();

ok.setId(excel.get(i).getTestid().toString());

ok.setContent(excel.get(i).getNaturetext());

ok.setNode(excel.get(i).getNaturename());

ok.setLeaf(Boolean.parseBoolean(excel.get(i).getSheetname()));//如果 String 参数不是 null 且在忽略大小写时等于"true"，则返回的 boolean 表示 true 值。

children.add(ok);

}

return SUCCESS;//返回数据children

}

}

**structs.xml配置**

&lt;?xml version="1.0" encoding="UTF-8"?&gt;

&lt;!DOCTYPE struts PUBLIC

    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"

    "http://struts.apache.org/dtds/struts-2.3.dtd"&gt; 

&lt;struts&gt;

&lt;constant name="struts.multipart.maxSize" value="20971520" &gt;&lt;/constant&gt;

&lt;package name="extjs4" extends="json-default" namespace="/"&gt;

         &lt;!--tree Test，返回类型json--&gt;

         &lt;action name = "getTreeData"  class ="excelTree.TreeData" method="GetTreenode"&gt;

         &lt;result type="json"&gt;&lt;/result&gt;

         &lt;/action&gt;

&lt;/package&gt;

&lt;/struts&gt;