平时开发中,经常用到异步加载树,每次用到都是重新下,虽然说每次实现的方式都换了,都不一样,但也是费时间,这次项目中又用到了,所以整理一下,以备后用。这次用到了jquery插件 easyui-tree,还是挺方便的,展现的是一棵异步产品树,tree.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <% String path=request.getContextPath(); %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>产品树</title> <link type="text/css" rel="stylesheet" href="<%=path%>/css/easyui/themes/default/easyui.css"> <link type="text/css" rel="stylesheet" href="<%=path%>/css/easyui/themes/icon.css"> <script type="text/javascript" src="<%=path%>/css/easyui/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="<%=path%>/css/easyui/jquery.easyui.min.js"></script> <script type="text/javascript"> $(function(){ $('#tt').tree({ url: '<%=path%>/meta/productCodeTree.action' }); }); </script> </head> <body> <ul id="tt"></ul> </body> </html>
服务端代码,用了struts2,通过json方式返回(注意,客户端会默认将节点id传给服务端,所以树节点都必须带id属性):
public void productCodeTree(){
try {
ProductCodeExample pce = new ProductCodeExample();
pce.setOrderByClause(" product_py ");
if(!StringUtil.isNullOrEmpty(id)){
pce.createCriteria().andParentCodeEqualTo(id);
}else{
pce.createCriteria().andParentCodeIsNull();
}
List<ProductCode> pcList = this.productCodeDao.selectByExample(pce);
List<Map<String,Object>> items = new ArrayList<Map<String,Object>>();
for(ProductCode pc:pcList){
Map<String,Object> item = new HashMap<String,Object>();
item.put("id", pc.getProductCode());
item.put("text", pc.getProductName());
pce.clear();
pce.createCriteria().andParentCodeEqualTo(pc.getProductCode());
if(productCodeDao.countByExample(pce)>0)
item.put("state", "closed");
items.add(item);
}
JSONArray json = JSONArray.fromObject(items);
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("application/json;charset=UTF-8");
response.setCharacterEncoding("utf-8");
response.setHeader("Charset", "utf-8");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().println(json.toString());
} catch (IOException e) {
e.printStackTrace();
}
}