jquery ajax调用不发送cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7911710/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:26:21  来源:igfitidea点击:

jquery ajax call not sending cookie

jqueryajax

提问by LordZardeck

I have a jQuery ajax call across a subdomain that works correctly except it's not sending the cookie. Is there any way to accomplish this?

我有一个跨子域的 jQuery ajax 调用,它可以正常工作,但不发送 cookie。有什么办法可以做到这一点吗?

采纳答案by Matthew

This sounds like expected behavior to me. Cookies are per domain (and that includes subdomains). But I think you can force it with something like this:

这对我来说听起来像是预期的行为。Cookie 是针对每个域的(包括子域)。但我认为你可以用这样的方式强制它:

$.ajax({
   headers: {'Cookie' : document.cookie },
   url: "sub.domain.com",
   success: function(){ ...

This is totally untested so let me know if it works ;)

这是完全未经测试的,所以让我知道它是否有效;)

EDIT: Actually it looks like its not possible at all... look here: How do I SET a Cookie (header) with XMLHttpRequest in JavaScript?you might be SOL

编辑:实际上它看起来根本不可能......看这里:如何在 JavaScript 中使用 XMLHttpRequest 设置 Cookie(标头)?你可能是SOL

But it think you can set the cookies in php so that they are valid across all your subdomains. Something like this:

但它认为您可以在 php 中设置 cookie,以便它们在您的所有子域中都有效。像这样的东西:

ini_set('session.cookie_domain', '.example.com')

Note the '.' before the domain - that will set the cookie for example.com and all its subdomains.

注意“.” 在域之前 - 这将为 example.com 及其所有子域设置 cookie。

You can set session.cookie_domain in your app using the above or set it in your php.ini.

您可以使用上面的方法在您的应用程序中设置 session.cookie_domain 或在您的 php.ini 中设置它。

The above is stolen from here

以上是从这里来的

回答by Tormod Hystad

Shouldn't this work if you use a CORScapable browser and set the withCredentialsattribute?

如果您使用支持CORS 的浏览器并设置withCredentials属性,这不应该工作吗?

See HTTP Cookies and Ajax requests over HTTPS

请参阅通过 HTTPS 的 HTTP Cookie 和 Ajax 请求