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

Not able to access cookie in javascript at path /

本文关键字:访问 cookie 路径 javascript      更新时间:2023-09-26

我使用jQuery访问/设置cookie。我在路径/处种植了一个名为CookieNo1的cookie。

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

cookie值被存储,我在firefox cookie上手动检查了该值。现在,当我尝试访问相同的cookie时,使用url localhost:8080/audi/products使用$.cookie('CookieNo1');

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

我所需要的是$.cookie('CookieNo1')返回以前的cookie值而不是null。提前感谢

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

在JavaScript:

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

max-age设置cookie的最长生存时间,单位为秒。

<标题>编辑

引用自注释:

@RobW我使用jquery在页面上添加了cookiehttp://localhost:8080/audi与代码$.cookie("asdftraffic", valueToSet, { expires: 30, path: '/', secure: true });我试图从url http://localhost:8080/audi/products检索cookie使用'$.cookie('asdftraffic');'返回null

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

首先设置cookie:

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

然后你得到饼干:

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就可以了