`
xiajin2080
  • 浏览: 35977 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论
  • Airflare: 你这也不对啊,各种报错啊!DocumentHelper哪来的啊 ...
    XML读写
  • myali88: 为什么我用$.getJSON请求返回的始终是一个JSON格式的 ...
    jQuery+JSON

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>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics