一.跨域方案
1.JSONP跨域
(1)前端发起jQuery ajax 的get请求
$.getJSON(
"http://localhost:8080/test/test.do?callback=?",
function(json){
alert(json[0].name);
}
);
(2)后台返回数据
String callback = request.getParameter("callback");
out.print(callback+"([ { name:'nicke',age:'19'},{ name:'hery',age:'20'}] );");
out.print(callback);
2.设置response跨域
response.setHeader("Access-Control-Allow-Origin", "http://www.test.com");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
3.将跨域的请求,通过后台发起http请求,然后再返回给前台
4.通过nginx转发
二.跨域经典案例
1.A.com,B.com 跨域共享cookie
方案:iframe+window.name
2.test1.A.com请求test2.A.com里面的服务,该服务要拿到test1.A.com里面的cookie
方案:jsonp
总结:推荐1,2,其实2不安全是伪命题,设置好允许跨域的域名就行