1、原生ajax请求方式:var xhr = new XMLHttpRequest();
xhr.open("POST", "http://xxxx.com/demo/b/index.php", true);
xhr.withCredentials = true; //支持跨域发送cookies
xhr.send();
2、jquery的ajax的post方法请求:$.ajax({
type: "POST",
url: "http://xxx.com/api/test",
dataType: 'json',
// 允许携带证书
xhrFields: {
withCredentials: true
},
// 允许跨域
crossDomain: true,
success:function(){
},
error:function(){
}
})
3、服务器端设置:header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: http://www.xxx.com");
4.通过P3P头实现跨域设置cookie
PHP的setcookie函数可以设置域,但是只能在当前域内,如果出现多域可由如下办法处理:
实现原理:
www.b.com/set_cookie.php 在b域名下设置a域名的cookie
www.a.com/get_cookie.php 在a域名下获取cookie
print_r($_COOKIE);
www.a.com/set_cookie.php 在a域名下设置a域名的cookie
header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
setcookie("test", "test value", time()+3600, "/");
实现过程:
访问www.b.com/set_cookie.php,然后访问www.a.com/get_cookie.php就可以获取cookie
其实,我在chrome不用P3P头也可以获取到cookie,但是IE不行,加上P3P头,IE也可以了。
P3P(Platform for Privacy Preferences)正是一种可以提供这种个人隐私保护策略,一般浏览器都支持P3P协议。P3P header允许跨域访问隐私数据,从而可以跨域set-cookie成功
-----------------------------------------------------
转载请注明来源此处
原地址:#