这几天项目中要用到树型结构,正好项目中用到了JQuery,所以就在网上找依赖JQuery的JS树,最终选择了 jquery.treeview.js,原因之一,它是JQuery官方发布的JS库,另一方面,看了一下它的文档,使用起来也是很简单的。经过一个小时的研究,终于搞定,现把它的使用方法做个简要的说明,以做笔记。
要使用jquery.treeview.js,当然第一步是要把它下载下来,放入自己的工程中,然后在页面文件中引进 jquery.js,jquery.cookie.js,jquery.treeview.js,jquery.treeview.async.js四个库文件,其中最后一个是要使用异步加载结点的时候,要用到的,我的项目中已经用到了这个功能,在初始化树的时候,只加载顶层的数据,当点击顶层结点的时候,才会去加载下一层的结点,所有的数据都是通过ajax去后台取得到数据。
将库文件引入后,下一步就是要定义一个列表UL:如这样:
- <ul id="categorys"></ul>
<ul id="categorys"></ul>
树数据将会加载到这个UL里面
- <script type="text/javascript">
- $(document).ready(function(){
- $("#categorys").treeview({
- url: "category!ajaxTreeView"
- });
- });
- </script>
<script type="text/javascript"> $(document).ready(function(){ $("#categorys").treeview({ url: "category!ajaxTreeView" }); }); </script>
这里面的意思就是当文档加载完成后,向后台CategoryAction获取数据,注意后台输出的数据必须是json格式的数据。
下一步就是后台CategoryAction的数据输出部分了:
- response.setHeader("Cache-Control", "no-cache");
- response.setContentType("text/json;charset=UTF-8");
- try {
- request.setCharacterEncoding("utf-8");
- } catch (UnsupportedEncodingException e1) {
- e1.printStackTrace();
- }
response.setHeader("Cache-Control", "no-cache");
response.setContentType("text/json;charset=UTF-8");
try {
request.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
要将contenttype设置为"text/json",第一次加载初始数据的时候,会向这个CategoryAction传递一个 get参数:root=source,所以后台可以判断root参数是否是source,如果是source,则代表是第一次加载数据,如果不是 source,则root参数传递的則是树结点的id.
数据格式如下:
- [
- {
- "text": "1. Pre Lunch (120 min)",
- "expanded": true,
- "classes": "important",
- "children":
- [
- {
- "text": "1.1 The State of the Powerdome (30 min)"
- },
- {
- "text": "1.2 The Future of jQuery (30 min)"
- },
- {
- "text": "1.2 jQuery UI - A step to richnessy (60 min)"
- }
- ]
- },
- {
- "text": "2. Lunch (60 min)"
- },
- {
- "text": "3. After Lunch (120+ min)",
- "children":
- [
- {
- "text": "3.1 jQuery Calendar Success Story (20 min)"
- },
- {
- "text": "3.2 jQuery and Ruby Web Frameworks (20 min)"
- },
- {
- "text": "3.3 Hey, I Can Do That! (20 min)"
- },
- {
- "text": "3.4 Taconite and Form (20 min)"
- },
- {
- "text": "3.5 Server-side JavaScript with jQuery and AOLserver (20 min)"
- },
- {
- "text": "3.6 The Onion: How to add features without adding features (20 min)",
- "id": "36",
- "hasChildren": true
- },
- {
- "text": "3.7 Visualizations with JavaScript and Canvas (20 min)"
- },
- {
- "text": "3.8 ActiveDOM (20 min)"
- },
- {
- "text": "3.8 Growing jQuery (20 min)"
- }
- ]
- }
- ]
[ { "text": "1. Pre Lunch (120 min)", "expanded": true, "classes": "important", "children": [ { "text": "1.1 The State of the Powerdome (30 min)" }, { "text": "1.2 The Future of jQuery (30 min)" }, { "text": "1.2 jQuery UI - A step to richnessy (60 min)" } ] }, { "text": "2. Lunch (60 min)" }, { "text": "3. After Lunch (120+ min)", "children": [ { "text": "3.1 jQuery Calendar Success Story (20 min)" }, { "text": "3.2 jQuery and Ruby Web Frameworks (20 min)" }, { "text": "3.3 Hey, I Can Do That! (20 min)" }, { "text": "3.4 Taconite and Form (20 min)" }, { "text": "3.5 Server-side JavaScript with jQuery and AOLserver (20 min)" }, { "text": "3.6 The Onion: How to add features without adding features (20 min)", "id": "36", "hasChildren": true }, { "text": "3.7 Visualizations with JavaScript and Canvas (20 min)" }, { "text": "3.8 ActiveDOM (20 min)" }, { "text": "3.8 Growing jQuery (20 min)" } ] } ]
格式说明:上面的1. Pre Lunch (120 min) 结点中:"expanded": true 代表这个结点下的child是展开的,children则是子结点的数据,节点3. After Lunch (120+ min)有8个子结点,其中子结点中有一个结点3.6 The Onion: How to add features without adding features (20 min),有一个id属性,同时hasChildren:true,表示其下面又有子结点,并且会向FetchProductTypeServlet传递参数为:root=id值,具体到这里就是root=36,那么点击这个结点的时候,后台就会接收到root=36这个值,然后我们就在具体应用中,通过数据库查询或者其它方式找到相对应的数据,然后将这些数据构造成treeview所需要的json数据,也即是上面所示格式的数据。
后台CategoryAction代码如下:
- public String ajaxTreeView(){
- Struts2Utils.renderText(categoryHelper.generateJTVJsonString());
- return null;
- }
public String ajaxTreeView(){
Struts2Utils.renderText(categoryHelper.generateJTVJsonString());
return null;
}
CategoryHelper代码如下:
- package com.prl.action.admin.helper;
- import java.util.List;
- import javax.servlet.http.HttpServletRequest;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Repository;
- import org.springside.modules.web.struts2.Struts2Utils;
- import com.prl.entity.Category;
- import com.prl.service.CategoryManager;
- import com.prl.service.jdbc.CategoryJdbcUtil;
- @Repository
- public class CategoryHelper {
- private static final Log log = LogFactory.getLog(CategoryHelper.class);
- @Autowired
- public CategoryManager categoryManager;
- @Autowired
- public CategoryJdbcUtil categoryJdbcUtil;
- // ========================= 产生jquery.treeview的jsonstring=================//
- public String generateJTVJsonString() {
- log.info("generateJTVJsonString start .....");
- HttpServletRequest request = Struts2Utils.getRequest();
- String id = request.getParameter("root");
- log.info("id:"+id);
- String output = "";
- if (id == null) {
- return "";
- } else if (id.equalsIgnoreCase("source")) {
- output = generateInitTreeString();
- } else {
- output = generateTreeChildNodeString(Long.parseLong(id));
- }
- log.info("generateJTVJsonString end,return:"+output);
- return output;
- }
- // 产生子节点jsonstring
- private String generateTreeChildNodeString(Long categoryId) {
- StringBuilder jsonString = new StringBuilder();
- jsonString.append("[");
- List<Category> categorys = categoryManager
- .findChildrenCategory(categoryId);
- if (categorys.isEmpty())
- return "";
- int i = 0;
- for (Category category : categorys) {
- if (i > 0) {
- jsonString.append(",");
- }
- jsonString.append(toJSONString(category));
- i++;
- }
- jsonString.append("]");
- return jsonString.toString();
- }
- private String toJSONString(Category category) {
- StringBuilder sb = new StringBuilder();
- sb.append(" {");
- sb.append(" \"text\": \"" + generateLinkString(category) + "\"");
- if (categoryJdbcUtil.hasChild(category)) {
- sb.append(", \"id\":\"" + category.getCatId() + "\"");
- sb.append(", \"hasChildren\":true");
- }
- sb.append(" }");
- return sb.toString();
- }
- private String generateLinkString(Category category) {
- String link = "<a href='javascript:on_cat_click("+category.getCatId()+");' >" + category.getCatName() + "</a>";
- //link = category.getCatName();
- return link;
- }
- private String generateInitTreeString() {
- StringBuilder jsonString = new StringBuilder();
- jsonString.append("[");
- List<Category> categorys = categoryManager.getRoot();
- int i = 0;
- for (Category category : categorys) {
- if (i > 0) {
- jsonString.append(",");
- }
- jsonString.append(toJSONString(category));
- i++;
- }
- jsonString.append("]");
- return jsonString.toString();
- }
- // ==================== 产生jquery.treeview的jsonstring 结束=================//
- }
package com.prl.action.admin.helper;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springside.modules.web.struts2.Struts2Utils;
import com.prl.entity.Category;
import com.prl.service.CategoryManager;
import com.prl.service.jdbc.CategoryJdbcUtil;
@Repository
public class CategoryHelper {
private static final Log log = LogFactory.getLog(CategoryHelper.class);
@Autowired
public CategoryManager categoryManager;
@Autowired
public CategoryJdbcUtil categoryJdbcUtil;
// ========================= 产生jquery.treeview的jsonstring=================//
public String generateJTVJsonString() {
log.info("generateJTVJsonString start .....");
HttpServletRequest request = Struts2Utils.getRequest();
String id = request.getParameter("root");
log.info("id:"+id);
String output = "";
if (id == null) {
return "";
} else if (id.equalsIgnoreCase("source")) {
output = generateInitTreeString();
} else {
output = generateTreeChildNodeString(Long.parseLong(id));
}
log.info("generateJTVJsonString end,return:"+output);
return output;
}
// 产生子节点jsonstring
private String generateTreeChildNodeString(Long categoryId) {
StringBuilder jsonString = new StringBuilder();
jsonString.append("[");
List<Category> categorys = categoryManager
.findChildrenCategory(categoryId);
if (categorys.isEmpty())
return "";
int i = 0;
for (Category category : categorys) {
if (i > 0) {
jsonString.append(",");
}
jsonString.append(toJSONString(category));
i++;
}
jsonString.append("]");
return jsonString.toString();
}
private String toJSONString(Category category) {
StringBuilder sb = new StringBuilder();
sb.append(" {");
sb.append(" \"text\": \"" + generateLinkString(category) + "\"");
if (categoryJdbcUtil.hasChild(category)) {
sb.append(", \"id\":\"" + category.getCatId() + "\"");
sb.append(", \"hasChildren\":true");
}
sb.append(" }");
return sb.toString();
}
private String generateLinkString(Category category) {
String link = "<a href='javascript:on_cat_click("+category.getCatId()+");' >" + category.getCatName() + "</a>";
//link = category.getCatName();
return link;
}
private String generateInitTreeString() {
StringBuilder jsonString = new StringBuilder();
jsonString.append("[");
List<Category> categorys = categoryManager.getRoot();
int i = 0;
for (Category category : categorys) {
if (i > 0) {
jsonString.append(",");
}
jsonString.append(toJSONString(category));
i++;
}
jsonString.append("]");
return jsonString.toString();
}
// ==================== 产生jquery.treeview的jsonstring 结束=================//
}
写完收功,希望能帮到正在使用这个treeview的朋友点小忙,自己以后再使用的时候,也可以再翻看一下这篇笔记,不至于搞忘记用法了。