1.原生Ajax請求方式,設置跨域請求附帶詳細參數php
var xhr = new XMLHttpRequest(); xhr.open("POST", "http://xxxx.com/demo/b/index.php", true); xhr.withCredentials = true; //支持跨域發送cookies xhr.send();
2.Jquery的Ajax請求,設置跨域附帶詳細參數web
$.ajax({ url: apiUrl.getCookie('getone'), data: { age: 11 }, xhrFields: { withCredentials:true //支持附帶詳細信息 }, crossDomain:true,//請求偏向外域 success: function (data) { alert(data); } });
3.服務端支持ajax
header("Access-Control-Allow-Credentials: true"); header("Access-Control-Allow-Origin: http://www.xxx.com");
或者webconfig中修改配置:segmentfault
<configuration> <system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="http://www.xxx.com" /> <add name="Access-Control-Allow-Methods" value="GET, POST" /> </customHeaders> </httpProtocol> </system.webServer> </configuration>
可以成功使用帶有 Cookie 的資源請求須要知足如下幾個條件:api
XMLHttpRequest
對象中指定了 withCredentials = true
跨域
服務器響應頭中 Access-Control-Allow-Credentials: true
服務器
服務器響應頭中 Access-Control-Allow-Origin
不能爲 *
cookie
其餘資料:http://segmentfault.com/a/1190000003693381?_ea=330169url
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORSspa