Struts2与JQurey ajax配合跨域请求


ajax

		$.ajax({
			url:"https://www-xxx.com/xxx/getCounselorDetailByHxCode",
			data: {xxx:x},
			dataType : 'jsonp',
			jsonp:"callback", 
			type:'post',
			
			error: function(data) { 
				console.log(data);
			},
			success:function(data){
			//	alert("suc");
				console.log(data);

			},
		});

其中 dataType指定为jsonp,jsonp 指定为 callback(随意),然后看struts2的配置:

		<action name="getCounselorDetailByHxCode"
			class="xxx" method="getCounselorDetailByHxCode">
			<result name="success" type="json">
				<param name="callbackParameter">callback</param>
				<param name="noCache">true</param>
			</result>
		</action>

其中,这一条

<param name="callbackParameter">callback</param>
中callback与ajax中jsonp字段设置相同

打印出来的 data 是 structs请求类实例的所有能够get的成员对象:

HXCodeList: null
HXType: null
content: null
counselorDetail: "success"
counselorDetailByHxCode: "success"
spResult: Object
typetypeStr: null
urlStr: null
userHXCode: "zeKNVeDc208"
userHXSubCode: null
userInfoId: null
__proto__: Object


js中,

data = data.spResult;
con += '<br><img src="' + data.body.counselorMap.userIcon + '" width="150px" />';


来访问结果



201611.1 补充:

jsonp方式跨域只能是字符串,所以struts在返回时应指定字符串变量



			<result name="success" type="json">
				<param name="root">jsonpResult</param>
				<param name="callbackParameter">URGOO_CALLBACK</param>
				<param name="noCache">true</param>
			</result>



其中,jsonpResult 为 String 类型

	public String actionMethod() throws Exception {
		spResult = serviceMethod();
		jsonpResult = JsonUtils.convert(spResult) ;
		return SUCCESS;
	}


除此之外,还有一种方法可以指定跨域:


在 actionMethod中,

		HttpServletResponse response = ServletActionContext.getResponse();
		response.setHeader("Access-Control-Allow-Origin", "*");


此时的前端代码完全不用改变。


原文地址:https://www.cnblogs.com/silyvin/p/9106848.html