來源於:阿賢博客javascript
cookie通常狀況下是無法跨域的,甚至POST請求通常狀況下都是沒法跨域的。
// 請求代碼示例 $.ajax({ url: url, type: "POST", data: metadata, dataType: 'json', xhrFields: { withCredentials: true }, crossDomain: true, success: function(){}, error: function(){} });
解決方法:服務器端設置,容許ajax請求跨域
## 服務端設置容許跨域代碼,eg: header("Access-Control-Allow-Credentials: true"); header("Access-Control-Allow-Origin: http://www.xxx.com"); ## 設置成功後,在接口請求的Response Headers會看到一下如下容許跨越信息 { Access-Control-Allow-Credentials:true Access-Control-Allow-Headers:x-requested-with,content-type Access-Control-Allow-Methods:POST Access-Control-Allow-Origin:http://www.aipai.com }
ajax跨域請求問題解決了,但當後端須要經過接口獲取cookies時,一樣存在cookies的跨域問題php
cookies的跨域解決方法:在請求中添加如下參數,請求頭信息便會附帶cookies信息
// 代碼 $.ajax({ ... xhrFields: { withCredentials: true }, ... });
來源於:阿賢博客html