我正在尝试使用 jQuery .ajax() 调用设置浏览器 cookie,但它不起作用。
console.log("before cookies:" + document.cookie);
$.ajax({
dataType: "json",
contentType: "application/json",
url: url,
type: "GET",
processData: false
}).then(function (data) {
console.log("after cookies:" + document.cookie);
});
在服务器端,系统会在响应中添加一个 Set-Cookie:
Access-Control-Allow-Headers Origin, X-Requested-With, Content-Type, Accept
Access-Control-Allow-Origin *
Content-Length 63
Content-Type application/json;charset=ISO-8859-1
Expires Thu, 01 Jan 1970 00:00:00 GMT
Set-Cookie myApiKey=testkey;Expires=Wed, 20-Aug-2014 18:11:57 GMT;Max-Age=31536000
输出为空:
before cookies:
after cookies:
这就是问题所在。主页位于一个子域,而 ajax 调用位于另一个 (api.mydomain.com)。但我认为我已经正确设置了服务器端的 CORS 标头。它应该工作。
Firebug 确实报告了 cookie 已设置,但不知何故它对外部页面不可见。有什么诀窍?