您的位置:首页 > 其它

跨域请求带cookie的解决方案

2016-06-02 14:12 302 查看
参考:http://blog.sina.com.cn/s/blog_87b9bbc70102vg18.html

         cookie一般情况下是没法跨域的,甚至POST请求一般情况下都是无法跨域的。但经过特殊处理后就可以了,这个处理需要客户端服务器的配合。

        一些请求可以通过jsonp的方式来实现跨域,但如果是非幂等的请求,还是需要POST的。处理如下:

服务器端设置:

header("Access-Control-Allow-Credentials: true");

header("Access-Control-Allow-Origin: http://www.xxx.com");
客户端请求的时候带上withCredentials参数,代码如下:
原生ajax:

var xhr = new XMLHttpRequest();
xhr.open("POST", "http://xxxx.com/demo/b/index.php", true);
xhr.withCredentials = true; //支持跨域发送cookies
xhr.send();

jquery ajax:
$.ajax({
type: "POST",
url: "http://xxx.com/api/test",
dataType: 'jsonp',
xhrFields: {
withCredentials: true
},
crossDomain: true,
success:function(){},
error:function(){}
})
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  跨域 cookie