Struts2+JQuery+JSON

1.Action
package com.fayhong.action.basicdata;

import java.util.List;

import org.apache.struts2.ServletActionContext;

import net.sf.json.JSONArray;

import com.fayhong.model.Country;
import com.fayhong.service.basicdata.BasicDataService;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

public class JsonAction extends ActionSupport{

	
	private BasicDataService basicDataService;
	private String countryJSON;
	
	public String findCountryList() {
		
		StringBuffer sb = new StringBuffer();
		String number = ServletActionContext.getRequest().getParameter("number");
		List countryList = basicDataService.findCountry(null,number);
		if (countryList.size() > 0) {
			
			sb.append("{");
			for (int i = 0; i < countryList.size(); i++) {
				Country country = (Country) countryList.get(i);
				sb.append(country.getCountryId());
				sb.append(":");
				sb.append("\"");
				sb.append(country.getCountryId());
				sb.append("\"");
				if (i != (countryList.size() - 1))
					sb.append(",");
			}
			sb.append("}");
		}
		
		JSONArray array = new JSONArray().fromObject(countryList);
		countryJSON=array.toString();
//		cityJSON = sb.toString();// 返回的数据
		System.out.println(sb.toString());
		System.out.println("cityJSON=="+countryJSON);
		return Action.SUCCESS;
	}

	public void setBasicDataService(BasicDataService basicDataService) {
		this.basicDataService = basicDataService;
	}

	public String getCountryJSON() {
		return countryJSON;
	}

	public void setCountryJSON(String countryJSON) {
		this.countryJSON = countryJSON;
	}
	
}


2.xml
	<package name="sajax" extends="json-default">
        <action name="findCountryList" method="findCountryList" class="com.fayhong.action.basicdata.JsonAction">
            <result type="json" />
        </action>
	</package>


3.jsp
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>

	<head>
		<meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
		<title>test jQuery</title>
	
		<script src="scripts/jquery/jquery-1.3.2.min.js" type="text/javascript"></script>
		
		<script>
			$(document).ready(function (){
				
				$('#jsons').click(function (){
				
				var url = "findCountryList.action";
				 
				$.getJSON(url,{number:"CHA"},function call(data){  
				 
					 alert(data.countryJSON);
				 
				 });
				
				
				});
			});
		</script>
	</head>
	
	
	<body>
		<input type="text" id="jsons"  value="json"/>
	</body>

</html>

你可能感兴趣的:(apache,jquery,jsp,xml,json)