前端:
以 jQuery 為例,需要加入
復制代碼 代碼如下:
xhrFields: {
withCredentials: true
},
crossDomain: true,
$.ajax({
type: postType,
url: url,
data: postData || '',
xhrFields: {
withCredentials: true
},
crossDomain: true,
success: function () {
successCallback.apply(scope || this, arguments);
},
failureCallback: function () {
failureCallback.apply(scope || this, arguments);
},
dataType: dataType
});
伺服器端:
以 PHP 為例:
復制代碼 代碼如下:
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Origin: https://m.z.com');
依自己的情況而定
跨域請求時 cookie 會丟失,是因為瀏覽器預設不會在跨來源請求中帶上憑證。前端只要在 jQuery 的 $.ajax 中設定 xhrFields.withCredentials 為 true 並開啟 crossDomain,後端 PHP 再回傳 Access-Control-Allow-Credentials 與明確的 Access-Control-Allow-Origin(注意不能用萬用字元,須指定具體來源),cookie 就能正常隨請求送出。以上就是解決 Ajax 跨域請求時 cookie 丟失的處理方案,希望大家能夠喜歡。