GET请求jsonp示例

前端之家收集整理的这篇文章主要介绍了GET请求jsonp示例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

众所周知GET请求可以用jsonp的方式解决跨域问题,下面会给出一个jsonp请求的示例。

1.后台接口

	@Path("getscene")
	@MClientHandler
	public ContentResult getSceneTable() {
		HttpServletRequest request = beat.getRequest();
		HttpServletResponse response = beat.getResponse();
		response.addHeader("Access-Control-Allow-Origin","*"); 
		response.addHeader("Access-Control-Allow-Credentials","true");
		response.addHeader("Access-Control-Allow-Methods","Get,Post,OPTIONS");
		response.addHeader("Access-Control-Request-Headers","X-Custom-Header");
				
		List <GulRecallSceneEntity> sceneList = GulRecallService.getSceneEntity();
		String sceneData = CommonService.tranObjectToString(sceneList);
		logger.info("sceneData=" + sceneData);
		
		String jsonp = request.getParameter("callback");  //后端接口支持jsonp
		return new ContentResult(jsonp + "(" + sceneData + ")" );  //后端接口支持jsonp
		//return new ContentResult(sceneData);
	}

2. 前端axaj请求

$.ajax({
	type : "GET",url : "http://xxx/getscene",contentType: "application/json;charset=utf-8",dataType:"jsonp",//请求支持jsonp
	data:'',jsonp:'callback',//请求支持jsonp
	success : function (msg) {			
		//TODO
	},error:function(){
		alert("错误");
	}
});

猜你在找的Json相关文章