无法在路径中的javascript中访问cookie

时间:2011-10-01 14:07:16

标签: javascript jquery cookies

我正在使用jQuery来访问/设置cookie。我在路径CookieNo1种植了名为/的Cookie。

我使用网址localhost:8080/audi种植了这个。

存储cookie值,我在firefox cookie上手动检查。现在,当我尝试使用localhost:8080/audi/products

的网址$.cookie('CookieNo1');访问相同的Cookie时

这似乎无法检索cookie的值。它返回一个空值。但是,当我尝试使用相同的localhost:8080/audi/products url编写cookie时,它会覆盖以前的cookie值。请帮我解决这个问题。

我需要的只是$.cookie('CookieNo1')来返回之前的cookie值而不是null。 提前致谢

2 个答案:

答案 0 :(得分:4)

您必须设置到期日期。否则,cookie将在会话结束时删除。在JQuery中:$("CookieNo1", "value", {expires: 7})(此cookie保留7天)。

在JavaScript中:

document.cookie = "CookieNo1=value; max-age=604800";

max-age设置Cookie的最长生命周期,以秒为单位。

修改

引用评论:

  

@RobW我在页面上使用jquery添加了cookie   我尝试使用代码$.cookie("asdftraffic", valueToSet, { expires: 30, path: '/', secure: true });的{​​{3}}   从网址http://localhost:8080/audi中检索Cookie   使用返回null的'$.cookie('asdftraffic');'

您的问题是由secure: true引起的。此属性要求cookie通过安全连接(https)传输。如果您没有使用加密连接,请删除secure: true标记。

答案 1 :(得分:1)

首先设置cookie:

var myvalue = 100, 2000, 300;
$.cookie("mycookie", myvalue);

然后你得到了cookie:

var getmycookie = $.cookie("mycookie");
    var myvalues = getmycookie.split(",");
    var firstval = myvalues[0];
    var secondval = myvalues[1];
    var thirdval = myvalues[2];

不应该更难。 如果未指定过期,则会在会话结束时删除cookie,即当浏览器关闭时。

编辑:您还可以指定路径:

$.cookie("mycookie", myvalue, {
expires : 10,           //expires in 10 days

path    : '/products',          //The value of the path attribute of the cookie 
                       //(default: path of page that created the cookie).

domain  : 'http://localhost:8080',  //The value of the domain attribute of the cookie
                       //(default: domain of page that created the cookie).

secure  : true          //If set to true the secure attribute of the cookie
                       //will be set and the cookie transmission will
                       //require a secure protocol (defaults to false).
});

我认为这样的事情可以做到:

var myvalue = 100, 2000, 300;
$.cookie("mycookie", myvalue, {path : '/audi/products'});

哦,当浏览器关闭时会话结束,而不是在页面被卸载时会话结束,所以会话cookie就可以了。