Analysis of jquery easyui tree Asynchronous Loading Child Node Problem

  • 2021-08-03 08:08:45
  • OfStack

Trees in easyui can be built from tags or by specifying an URL attribute to read data. If you want to build an asynchronous tree, you need to specify an id attribute value for each node, so that the id parameter is automatically passed to the background when the data is loaded.


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

Write foreground code:


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

For testing, establish a data model of 1 node:


@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;
  }
}

Write the controller code in the background:


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);
  }
}

Official website example address: http://www.jeasyui.com/tutorial/tree/tree2.php

demo Download: easyui-tree2_jb51. rar

Say important things three times! ! !


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

method1 must use POST, and GET should use a variable after URL for timestamp processing.

method1 must use POST, and GET should use a variable after URL for timestamp processing.

POST must be used for method1, and GET should be timestamped with a variable after URL.


Related articles: