跨域请求带cookie的解决方案

参考: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(){}
})



你可能感兴趣的:(前端)