jquery-easyui中創建異步加載樹

easyui中的樹可以從標記中建立,也可以通過指定一個URL屬性讀取數據建立。如果想建立一棵異步樹,需要爲每個節點指定一個id屬性值,這樣在加載數據時會自動向後臺傳遞id參數。

 

<ul id="tt"></ul>

編寫前臺代碼:

$('#tt').tree({
    url:'/demo2/node/getNodes'    // The url will be mapped to NodeController class and getNodes method
});

爲測試用,建立一個節點的數據模型:

@Table(name="nodes")
public class Node extends ActiveRecordBase{
    @Id public Integer id;
    @Column public Integer parentId;
    @Column public String name;
 
    public boolean hasChildren() throws Exception{
        long count = count(Node.class, "parentId=?", new Object[]{id});
        return count > 0;
    }
}

編寫後臺的控制器代碼:

public class NodeController extends ApplicationController{
    /**
     * get nodes, if the 'id' parameter equals 0 then load the first level nodes,
     * otherwise load the children nodes
     * @param id the parent node id value
     * @return the tree required node json format
     * @throws Exception
     */
    public View getNodes(int id) throws Exception{
        List<Node> nodes = null;
 
        if (id == 0){    // return the first level nodes
            nodes = Node.findAll(Node.class, "parentId=0 or parentId is null", null);
        } else {    // return the children nodes
            nodes = Node.findAll(Node.class, "parentId=?", new Object[]{id});
        }
 
        List<Map<String,Object>> items = new ArrayList<Map<String,Object>>();
        for(Node node: nodes){
            Map<String,Object> item = new HashMap<String,Object>();
            item.put("id", node.id);
            item.put("text", node.name);
 
            // the node has children, 
            // set the state to 'closed' so the node can asynchronous load children nodes 
            if (node.hasChildren()){
                item.put("state", "closed");
            }
            items.add(item);
        }
 
        return new JsonView(items);
    }
}

運行測試程序:http://localhost:8080/demo2/

 

 

原文及代碼下載地址:http://jquery-easyui.wikidot.com/tutorial:tree2

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章