AJAX 响应可以设置 cookie 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3340797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can an AJAX response set a cookie?
提问by Billworth Vandory
Can an AJAX response set a cookie? If not, what is my alternative solution? Should I set it with Javascript or something similar?
AJAX 响应可以设置 cookie 吗?如果没有,我的替代解决方案是什么?我应该用 Javascript 或类似的东西设置它吗?
采纳答案by this. __curious_geek
Yes, you can set cookie in the AJAX request in the server-side code just as you'd do for a normal request since the server cannot differentiate between a normal request or an AJAX request.
是的,您可以在服务器端代码的 AJAX 请求中设置 cookie,就像您对普通请求所做的一样,因为服务器无法区分普通请求或 AJAX 请求。
AJAX requests are just a special way of requesting to server, the server will need to respond back as in any HTTP request. In the response of the request you can add cookies.
AJAX 请求只是向服务器发出请求的一种特殊方式,服务器需要像在任何 HTTP 请求中一样进行响应。在请求的响应中,您可以添加 cookie。
回答by Strelok
According to the w3 spec section 4.6.3 for XMLHttpRequesta user agent should honor the Set-Cookie header. So the answer is yes you should be able to.
根据XMLHttpRequest的w3 规范第 4.6.3 节,用户代理应遵守 Set-Cookie 标头。所以答案是肯定的,你应该可以。
Quotation:
引述:
If the user agent supports HTTP State Management it should persist, discard and send cookies (as received in the Set-Cookie response header, and sent in the Cookie header) as applicable.
如果用户代理支持 HTTP 状态管理,它应该在适用时保留、丢弃和发送 cookie(在 Set-Cookie 响应标头中接收,并在 Cookie 标头中发送)。
回答by Bogdan St?ncescu
For the record, be advised that all of the above is (still) true only if the AJAX call is made on the same domain. If you're looking into setting cookies on another domain using AJAX, you're opening a totally different can of worms. Reading cross-domain cookies does work, however (or at least the server serves them; whether your client's UA allows your code to access them is, again, a different topic; as of 2014 they do).
作为记录,请注意,仅当 AJAX 调用是在同一个域上进行时,上述所有内容(仍然)才是正确的。如果您正在考虑使用 AJAX 在另一个域上设置 cookie,那么您将打开一个完全不同的蠕虫罐头。然而,读取跨域 cookie 确实有效(或者至少服务器为它们提供服务;您的客户端的 UA 是否允许您的代码访问它们,这又是一个不同的主题;截至 2014 年,它们确实如此)。
回答by Phil
Also check that your server isn't setting secure cookies on a non http request. Just found out that my ajax request was getting a php session with "secure" set. Because I was not on https it was not sending back the session cookie and my session was getting reset on each ajax request.
还要检查您的服务器是否没有在非 http 请求上设置安全 cookie。刚刚发现我的 ajax 请求正在获取一个带有“安全”设置的 php 会话。因为我不在 https 上,所以它没有发回会话 cookie,而且我的会话在每个 ajax 请求上都被重置。

