用etmvc framework返回json数据。
创建HTML标记
<ul id="tt"></ul>
创建jQuery代码
我们使用url属性来指向远程数据
$('#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;
}
}
写控制代码
如果node是子,记住设置node状态为closed。
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);
}
}
数据配置实例
domain_base_class=com.et.ar.ActiveRecordBase
com.et.ar.ActiveRecordBase.adapter_class=com.et.ar.adapters.MySqlAdapter
com.et.ar.ActiveRecordBase.driver_class=com.mysql.jdbc.Driver
com.et.ar.ActiveRecordBase.url=jdbc:mysql://localhost/mydb
com.et.ar.ActiveRecordBase.username=root
com.et.ar.ActiveRecordBase.password=soft123456
com.et.ar.ActiveRecordBase.pool_size=0
部署
· 建立MySQL数据库
· 从'/db/item.sql'导入测试表数据,表名是'item'.
· 按需要改变数据库配置,配置文件在/WEB-INF/classes/activerecord.properties中。
· 运行程序