javascript jQuery:为两个域设置 cookie

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

jQuery: Set cookie for two domains

javascriptjquerycookiessetcookie

提问by Artpixler

I want to set a cookie to a domain, but it should be available for a sub domain as well.

我想为域设置 cookie,但它也应该可用于子域。

e.g. www.mydomain.com and sub.mydomain.com

例如 www.mydomain.com 和 sub.mydomain.com

When I set the cookie to the main domain it doesn't exist for the subdomain.

当我将 cookie 设置为主域时,它不存在于子域中。

I use jQuery cookie Plugin: https://code.google.com/p/cookies/wiki/Documentation

我使用 jQuery cookie 插件:https: //code.google.com/p/cookies/wiki/Documentation

My idea was to store it for both domains, have a look at the code:

我的想法是为两个域存储它,看看代码:

var newOptions = {
    domain: 'sub.mydomain.com',
    secure: true
}
jaaulde.utils.cookies.set('name', 'value');
jaaulde.utils.cookies.set('name', 'value', newOptions );

What do I wrong?

我怎么了?

回答by Jon

Cash2m is correct, you should be able to specify a . to reach your subdomains:

Cash2m 是正确的,您应该能够指定一个 . 访问您的子域:

$.cookie('key', 'value', { domain: '.mydomain.com' });

回答by Laurent S.

Well, if you want to extend it to the domain and not only a specific subdomain, just use

好吧,如果您想将其扩展到域而不仅仅是特定的子域,只需使用

domain : 'mydomain.com'

instead of :

代替 :

domain: 'sub.mydomain.com'