1. 程式人生 > >jquery easyui tree動態載入-服務端struts返回json資料

jquery easyui tree動態載入-服務端struts返回json資料

第一種方法:

js: 

<script type="text/javascript">
	$(function() {
		$(document).ready(function() {

			$.post("./test/tree.action", {}, function(json) {

				$("#tt").tree({
					data : json.itemsList,
					onClick : function(node) {
						$.post("./test/tree.action", {
							"id" : node.id
						}, function(json) {
							$('#tt').tree('append', {
								parent : node.target,
								data : json.data
							});
						}, "json");

					}
				});
			}, "json");
		});
	});
</script>
</head>
<body>
	<ul id="tt"></ul>
</body>

struts:

action:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.json.annotations.JSON;

import com.opensymphony.xwork2.ActionSupport;

public class TreeAction extends ActionSupport {
	private List<Map<String, Object>> itemsList;
	
	private int id;

	@Override
	public String execute() throws Exception {
		
		itemsList = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < 5; i++) {
			Map<String, Object> item = new HashMap<String, Object>();
			item.put("id", i);
			item.put("text", i);
			item.put("state", "closed");
		//	item.put("children", itemsList2);
			itemsList.add(item);
		}

		return super.execute();
	}

	@JSON(serialize = true, name = "data")
	public List<Map<String, Object>> getItemsList() {
		return itemsList;
	}

	public void setItemsList(List<Map<String, Object>> itemsList) {
		this.itemsList = itemsList;
	}

}
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>

	<package name="test" extends="json-default" namespace="/test">
		<action name="tree"
			class="com.test.struts.TreeAction">
			<result name="success" type="json"></result>
		</action>
	</package>

</struts>    


第二種方法:

js:

<script type="text/javascript">
	$(function() {
		$(document).ready(function() {
			$("#tt2").tree({
				url : "test/tree.action"
			});

		});

	});
</script>
</head>
<body>
	<ul id="tt2"></ul>
</body>

struts:
public class TreeAction extends ActionSupport {

	private int id;

	@Override
	public String execute() throws Exception {
		//可根據id查詢相應節點

		itemsList = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < 5; i++) {
			Map<String, Object> item = new HashMap<String, Object>();
			item.put("id", i);
			item.put("text", i);
			item.put("state", "closed");
			// item.put("children", itemsList2);
			itemsList.add(item);
		}

		String data = JSONUtils.toJson(itemsList).toString();

		ServletActionContext.getResponse().getWriter().write(data);
		
		return null;
	}
//getter
//setter
}