您的位置:首页 > 其它

zTree异步加载简单demo

2012-07-10 17:51 197 查看
这几天花了些时间,试了试zTree自带的异步加载方式 还不错.

有个奇怪的问题:

无论我在服务器设置 setContentType("text/plain;charset=UTF-8")或是 setContentType("application/json;charset=UTF-8"),zTree都会把接收到的数据当json格式,除非不符合json格式.

(另:JSONBuilder是个简单的json处理类,适用于不复杂的数据格式)

以下是简单的demo

test2.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="css/zTreeStyle/zTreeStyle.css" type="text/css">
<script type="text/javascript" src="script/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="script/jquery.ztree.core-3.2.js"></script>
<script type="text/javascript" src="script/jquery.ztree.excheck-3.2.js"></script>
<title>无标题文档</title>

<script type="text/javascript">
var nodeIcon = "images/4.png";
var groupIcon = "images/1_open.png";

function initTree(){
var setting = {
check: {
enable: true
},
data: {
simpleData: {
enable: true
}
},
async: {
enable: true,
url:"http://localhost/web_test1/action/test2Action.jsp",
dataType: "text",
dataFilter: ajaxDataFilter,
autoParam:["id"]
}
};

/***/
var zNodes =[
{id:"userGroup:__ALL__", name:"全部用户组", open:true},
{pId:"userGroup:__ALL__", id:"userGroup:001", name:"用户组_001", isParent:true, open:false, icon:groupIcon},
{pId:"userGroup:__ALL__", id:"userGroup:002", name:"用户组_002", isParent:true, open:false, icon:groupIcon},
{pId:"userGroup:__ALL__", id:"hostGroup:001", name:"设备组_001", isParent:true, open:false, icon:groupIcon},
{pId:"userGroup:__ALL__", id:"hostGroup:002", name:"设备组_002", isParent:true, open:false, icon:groupIcon}
];
/***/

$.fn.zTree.init($("#myTree"), setting, zNodes);
}

function ajaxDataFilter(treeId, parentNode, data) {
//alert(data);
//alert( $(data).attr("count"));
var array = [];
//var jsonp = $.parseJSON(childNodes);
//var nc = parseInt($(jsonp).attr("count"));
var nc = parseInt($(data).attr("count"));
var _pId = parentNode.id;
var _id = null;
var _name = null;

//alert($(data).attr("id["+ i +"]"));
//alert("nc:"+nc);
//alert(parentNode.id);
for(var i=0; i<nc; i++){
//item = {pId:parentNode.id, id:$(jsonp).attr("id["+ i +"]"), name:$(jsonp).attr("name["+ i +"]"), isParent:false, open:true};
//item = {pId:parentNode.id, id:"test:"+i, name:"test_"+i, isParent:false, open:true};
_id = $(data).attr("id["+ i +"]");
_name = $(data).attr("name["+ i +"]");

array[i] = {pId:_pId, id:_id, name:_name, isParent:false, open:true, icon:nodeIcon};
}

return array;
}

function old_ajaxDataFilter(treeId, parentNode, childNodes) {
//alert(childNodes);
var txt = "";
var jsonp = $.parseJSON(childNodes);
var nc = parseInt($(jsonp).attr("count"));

for(var i=0; i<nc; i++){
txt += $(jsonp).attr("id["+ i +"]") + "<br/>";
}
alert(txt);

return null;
}

$(document).ready(function(){
initTree();
});
</script>

<style type="text/css">
.div_frame{
width:800px;
border: 1px solid #a5a4a4;
}

.div_tree{
width:300px;
height:200px;
overflow:auto;
border: 1px solid #a5a4a4;
}
</style>
</head>

<body>
<div class="div_frame">
<div class="div_tree">
<ul id="myTree" class="ztree"></ul>
</div>
</div>
</body>
</html>


test2Action.jsp

<%@ page language="java" contentType="text/html; charset=utf-8" %>
<%@ page pageEncoding="utf-8"%>
<%@ page import="java.util.List" %>
<%@ page import="java.util.LinkedList" %>
<%@ page import="java.io.PrintWriter" %>
<%@ page import="org.sl.json.JSONBuilder" %>
<%@ page import="java.util.Random" %>
<!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>Insert title here</title>
<%
// String json = "{\"count\":\"3\",\"id[0]\":\"id_0\",\"id[1]\":\"id_1\",\"id[2]\":\"id_2\"}";
//String json = "{\"count\":\"2\",\"id[0]\":\"id_0\",\"id[1]\":\"id_1\",\"name[0]\":\"name_0\",\"name[1]\":\"name_1\",}";
String json = null;
Random rand = new Random(System.currentTimeMillis());
int count = rand.nextInt(8)+2;
JSONBuilder js = new JSONBuilder();

js.put("count", ""+count);
for(int i=0; i<count; i++){
js.put("id["+ i +"]", "test:"+i);
js.put("name["+ i +"]", "test:"+i);
}

json = js.toJsonString();

String id = request.getParameter("id");
System.out.println("id:" + id);

//json => application/json text/x-json

// response.setContentType("text/plain;charset=UTF-8");
response.setContentType("application/json;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter pw = response.getWriter();
pw.write(json);
pw.flush();
pw.close();
%>
</head>
<body>

</body>
</html>


JSONBuilder.java

package org.sl.json;

import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;

/**
* 可以用来处理格式比较简单的json字符串
* @author shanl
*
*/
public class JSONBuilder {
//	private Properties dict = new Properties();
private Map<String,String> dict = new LinkedHashMap<String,String>(20);

/**
* 写入一个键/值对
* @param key
* @param value
*/
public void put(String key, String value){
this.dict.put(replaceJsonChar(key), replaceJsonChar(value));
}

private String replaceJsonChar(String str){
StringBuilder sb = new StringBuilder();
char[] chs = str.toCharArray();

for(char c: chs){
switch (c) {
case '\"':
sb.append("\\\"");
break;
case '\\':
sb.append("\\\\");
break;
case '/':
sb.append("\\/");
break;
case '\b':
sb.append("\\b");
break;
case '\f':
sb.append("\\f");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
default:
sb.append(c);
}
}

return sb.toString();
}

/**
* 返回键/值对列表
* @return
*/
public Map<String,String> getDict(){
return dict;
}

/**
* 返回键所对应的值
* @param key
* @return
*/
public String getValue(String key){
return dict.get(key);
}

/**
* 解析json格式字符串
* @param json
*/
public void parseJsonString(String json){
String _json = json;
String[] ss = null;
String[] tmp = null;

_json = _json.trim(); //去掉两端空格
_json = _json.substring(2); //去掉 {"
_json = _json.substring(0, _json.length()-2); //去掉 }"

ss = _json.split("\",\"");
for(String s: ss){
tmp = s.split("\":\"");
put(tmp[0], tmp[1]);
}
}

/**
* 将数据转换成json格式字符串
* @return
*/
public String toJsonString(){
String sb = "";
String key = null;
String value = null;
Iterator<String> keys = dict.keySet().iterator();
//		Enumeration keys = dict.propertyNames();

sb += "{";

while(keys.hasNext()){
key = keys.next();
value = dict.get(key);

sb += "\""+ key +"\":";
sb += "\""+ value +"\",";
}

if(sb.endsWith(",") ){
sb = sb.substring(0, sb.length()-1);
}

sb += "}";

return sb.toString();
}

public String toString(){
return toJsonString();
}
}


JSONBuilder测试类, Test2.java:

package test1;

import org.sl.json.JSONBuilder;

public class Test2 {
public static void main(String[] args){
t7();
//		t1();
}

static void t7(){
String str = "{\"count\":\"3\",\"id[0]\":\"id_0\",\"id[1]\":\"id_1\",\"id[2]\":\"id_2\"}";
JSONBuilder js = new JSONBuilder();
js.parseJsonString(str);

System.out.println(js.getValue("id[1]"));
}

static void t6(){
JSONBuilder js = new JSONBuilder();
js.put("abc\"sasas", "sasjajsas\"saas");

System.out.println(js.toJsonString());
}

static void t5(){
String str = "{\"count\":\"3\",\"id[0]\":\"id_0\",\"id[1]\":\"id_1\",\"id[2]\":\"id_2\"}";
JSONBuilder js = new JSONBuilder();

js.parseJsonString(str);
System.out.println(js.getValue("count"));
System.out.println(js.getValue("id[0]"));
}

static void t4(){
String str = "'{\"count\":\"3\",\"id[0]\":\"id_0\",\"id[1]\":\"id_1\",\"id[2]\":\"id_2\"}'";
JSONBuilder js = new JSONBuilder();

js.parseJsonString(str);
System.out.println(js.getValue("count"));
}

static void t3(){
String str = "'{\"count\":\"3\",\"id[0]\":\"id_0\",\"id[1]\":\"id_1\",\"id[2]\":\"id_2\"}'";
String[] ss = str.split("\",\"");

for(String s: ss){
System.out.println(s);
}
}

static void t2(){
JSONBuilder js = new JSONBuilder();
String str = "'{\"count\":\"3\",\"id[0]\":\"id_0\",\"id[1]\":\"id_1\",\"id[2]\":\"id_2\"}'";
str = str.trim();
str = str.substring(3);
str = str.substring(0, str.length()-3);

System.out.println(str);
System.out.println();

String[] tmp = null;
String[] ss = str.split("\",\"");

for(String s: ss){
tmp = s.split("\":\"");
js.put(tmp[0], tmp[1]);
}

System.out.println(js.getValue("count"));
}

static public void t1(){
JSONBuilder js = new JSONBuilder();
int c = 3;

js.put("count", c+"");

for(int i=0; i<c; i++){
js.put("id["+ i +"]", "id_"+i);
}

System.out.println(js.toJsonString());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: