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請求,設置跨域附帶詳細參數
$.ajax({ url: apiUrl.getCookie('getone'), data: { age: 11 }, xhrFields: { withCredentials:true //支持附帶詳細信息 }, crossDomain:true,//請求偏向外域 success: function (data) { alert(data); } });
3.服務端支持
header("Access-Control-Allow-Credentials: true"); header("Access-Control-Allow-Origin: http://www.xxx.com");
或者webconfig中修改配置:
<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 的資源請求需要滿足以下幾個條件:
-
XMLHttpRequest對象中指定了withCredentials = true -
服務器響應頭中
Access-Control-Allow-Credentials: true -
服務器響應頭中
Access-Control-Allow-Origin不能為*
其他資料:http://segmentfault.com/a/1190000003693381?_ea=330169
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
