无法在路径 / 的 javascript 中访问 cookie
我正在使用 jQuery 来访问/设置 cookie。我在路径 /
处植入了一个名为 CookieNo1
的 cookie。
我使用 url localhost:8080/audi
植入了它。
cookie 值已存储,我在 firefox cookie 上手动检查了该值。现在,当我尝试访问同一个 cookie 时,使用 url localhost:8080/audi/products
using $.cookie('CookieNo1');
这似乎并不检索 cookie 的值。它返回一个空值。但是,当我尝试使用相同的 localhost:8080/audi/products url 写入 cookie 时,它会覆盖以前的 cookie 值。请帮我解决这个问题。
我所需要的只是 $.cookie('CookieNo1')
返回之前的 cookie 值而不是 null。 提前致谢
I am using jQuery to access/set the cookies. I have planted a cookie named CookieNo1
at path /
.
I planted this using the url localhost:8080/audi
.
The cookie value is stored, which I checked manually on the firefox cookies. Now when I try to access the same cookie, using the url localhost:8080/audi/products
using $.cookie('CookieNo1');
This doesn't seem to retrieve the value of the cookie. It returns a null value. However when I try to write the cookie using the same localhost:8080/audi/products
url, it overwrites the previous cookie value. Please help me with this issue.
All I need is $.cookie('CookieNo1')
to return the previous cookie value instead of null.
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须设置到期日期。否则,cookie 将在会话结束时被删除。在 JQuery 中:
$("CookieNo1", "value", {expires: 7})
(此 cookie 保留 7 天)。在 JavaScript 中:
max-age
设置 cookie 的最长生命周期(以秒为单位)。编辑
引用评论:
您的问题是由
secure: true
引起的。此属性要求通过安全连接 (https
) 传输 cookie。如果您不使用加密连接,请删除secure: true
标志。You have to set the expiry date. Otherwise, the cookie is removed at the end of the session. In JQuery:
$("CookieNo1", "value", {expires: 7})
(this cookie stays for 7 days).In JavaScript:
max-age
sets the maximum lifetime of a cookie, in seconds.EDIT
Quote from comments:
Your issue is caused by
secure: true
. This attribute requires the cookie to be transmitted over a secure connection (https
). Remove thesecure: true
flag if you're not using an encrypted connection.首先你设置cookie:
然后你得到cookie:
应该不会太难。
如果未指定过期时间,则 cookie 将在会话结束时(即浏览器关闭时)被删除。
编辑:您还可以指定路径:
我认为类似这样的事情会做:
哦,会话在浏览器关闭时结束,而不是在页面卸载时结束,所以会话 cookie 就可以了。
First you set the cookie:
Then you get the cookie:
Should'nt be much harder.
When not specifying an expiration, the cookie is deleted on session end i.e. when the browser is closed.
EDIT: You can also specify the path:
I would think something like this would do:
Oh, and a session ends when the browser is closed, not when the page is unloaded, so a session cookie will do.