Ajax跨域目前有这几种方案:ngnix代理、jsonp、cors等方式。
由于jsonp对服务端和前端代码侵入太大暂不考虑,cors方式对于前后端代码的解决方式比较简单所以采用它,ajax跨域主要是在前后端的请求和响应设置http请求头“Access-Control-Allow-Origin”为“*”。
对于ie内核的浏览器
Ajax请求之前加入代码$.support.cors = true;
对于chrome内核的浏览器
Ajax请求中加入代码crossDomain : true,
参考代码
var url = contextPath + "/mallWap/rest/queryActiveById.do"; $.support.cors = true; $.ajax({ type : "POST", url : url, dataType : "json", contentType : "application/json;charset=UTF-8", crossDomain : true, headers: { "appId": localStorage.getItem("appId"), "appKey" : localStorage.getItem("appKey"), "appVersion" : localStorage.getItem("appVersion"), "clientId" : localStorage.getItem("clientId"), "accessToken": localStorage.getItem("accessToken") }, data : JSON.stringify({ "activeId":activeId }), success : function(data) {…}, error: function(XMLHttpRequest, textStatus, errorThrown) { } );
涉及到的请求中设置请求头response.addHeader("Access-Control-Allow-Origin", "*");
public class CorsFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)throws ServletException, IOException { response.addHeader("Access-Control-Allow-Origin", "*"); response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); response.addHeader("Access-Control-Allow-Headers", "origin, content-type, accept, x-requested-with, sid, mycustom, smuser"); filterChain.doFilter(request, response); } }
由于请求中存在其它业务的header参数目前的处理方式是在服务端响应的header中允许的key
response.addHeader("Access-Control-Allow-Headers", "origin, content-type, accept, x-requested-with, sid, mycustom, smuser , appId, appKey");