使用 Javascript 变量设置 cookie 域

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

Set cookie domain with Javascript variable

javascriptjquery

提问by CLiown

Im taking the domain from the HTML of the page using jQuery:

我使用 jQuery 从页面的 HTML 中获取域:

domainUrl = $("p.domain").text();

for the purposes of testing:

为测试目的:

<p class="domain">.vl3.co.uk</p>

Which is also the domain Im testing the script on.

这也是我测试脚本的域。

This then give an alert containing the correct domain:

然后给出一个包含正确域的警报:

alert(domainUrl);

I want to the use that variable to set the domain in a cookie:

我想使用该变量在 cookie 中设置域:

set_cookie('visible', 'no', 2020, 1, 1, '/', '+domainUrl+');

Here is the set cookie function:

这是设置cookie函数:

function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure ) {
  var cookie_string = name + "=" + escape ( value );
  if ( exp_y ) {
    var expires = new Date ( exp_y, exp_m, exp_d );
    cookie_string += "; expires=" + expires.toGMTString();
  }
  if ( path )
    cookie_string += "; path=" + escape ( path );
  if ( domain )
    cookie_string += "; domain=" + escape ( domain );
  if ( secure )
    cookie_string += "; secure";
  document.cookie = cookie_string;
}

Why doesnt the cookie domain get set?

为什么没有设置cookie域?

I think the problem is how im using the domainUrl variable when setting the cookie?

我认为问题是我在设置 cookie 时如何使用 domainUrl 变量?

回答by netadictos

It should be: set_cookie('visible', 'no', 2020, 1, 1, '/', domainUrl);

应该是: set_cookie('visible', 'no', 2020, 1, 1, '/', domainUrl);

Pls, try this extension, it works, it comprises all that:

请试试这个扩展,它有效,它包括所有内容:

http://plugins.jquery.com/project/Cookie

http://plugins.jquery.com/project/Cookie

Then you only have to write:

然后你只需要写:

$.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com' });

回答by nitin

Use jquery Annex library

使用jquery附件库

I think this is the best way to get and set cookies using jQuery:

我认为这是使用 jQuery 获取和设置 cookie 的最佳方式:

// cookie [writes and reads cookies]

//set cookie
$.cookie('kittencookie', 'fluffy', {expires : 7});

//get cookie
var kittenCookieValue = $.cookie('kittencookie');

For more details see documentation.

有关更多详细信息,请参阅文档