众所周知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("错误"); } });原文链接:https://www.f2er.com/json/288783.html