---
title: "jquery ajax json4 treeview动态加载"
author: "xujunJ2EE"
date: "2009-12-09T20:17:52Z"
tags: []
categories: ["Web前端"]
slug: "jquery-ajax-json4-treeview"
draft: false
lastmod: "2009-12-09T20:23:40Z"
id: 545017
url: "https://xujunj2ee.iteye.com/blog/545017"
---

```java

   <ul id="tree" class="filetree treeview-famfamfam">
   </ul>

```

动态加载的时候，只会在第一次展开的时候发送服务器，再次展开是不发送的，类似jquey的one事件处理。
treeview每次请求都是get请求，会自动带一个"root"的url参数，第一次是"source"。
以后的话都以li的id作为参数,即你在json数据中设置的"id"值。如果json中某个bool值的项目你不需要，就不写，设置false没有效果的。
还需要注意的是treeview的jquery.treeview.anync.js有一个bug，原来是：
current.children("span").addClass(this.classes);这样有异常的，要改成字符串形式，如下：
current.children("span").addClass(""+this.classes);

```java

response.setHeader("Cache-Control", "no-cache");   
		String parameter = request.getParameter("root");
		if (parameter != null)
		{
			//第一次加载的时候root是"source", 以后是id的值
			if (parameter.equals("source"))
			{
				try
				{
					JSONArray baseArray = new JSONArray();
					for (int i = 0; i < 3; i++)
					{
						JSONObject baseObject = new JSONObject();
						baseObject.append("text", "base"+i);
						baseObject.append("id", i);
						/*如果不需要某个设置就不写，设置false没有效果的*/
						//baseObject.append("expanded", true); 
						baseObject.append("classes", "folder");
						baseObject.append("hasChildren", true);
						baseArray.put(baseObject);
					}
					String json = baseArray.toString();
					System.out.println(json);
					response.setHeader("Cache-Control", "no-cache");   
					response.setContentType("application/json");
					byte[] bs = json.getBytes("utf-8");
					response.setContentLength(bs.length);
					OutputStream os = response.getOutputStream();
					os.write(bs);
					os.flush();
					os.close();
				}
				catch (JSONException e)
				{
					e.printStackTrace();
				}
			}
			else 
			{
				try
				{
					JSONArray childArray = new JSONArray();
					for (int i = 0; i < 2; i++)
					{
						JSONObject childObject = new JSONObject();
						childObject.append("text", "base is "+parameter+" child" + i);
						childObject.append("id", i);
						/* 如果不需要某个设置就不写，设置false没有效果的 */
						// baseObject.append("expanded", true);
						childObject.append("classes", "folder");
						childObject.append("hasChildren", true);
						childArray.put(childObject);
					}
					String json = childArray.toString();
					System.out.println(json);
					response.setHeader("Cache-Control", "no-cache");
					response.setContentType("application/json");
					byte[] bs = json.getBytes("utf-8");
					response.setContentLength(bs.length);
					OutputStream os = response.getOutputStream();
					os.write(bs);
					os.flush();
					os.close();
				}
				catch (JSONException e)
				{
					e.printStackTrace();
				}
			}
		}

```