如何将Cookie设置为可通过Javascript在整个域中访问 [英] How do you set a cookie to be accessible across the entire domain in Javascript

查看:81
本文介绍了如何将Cookie设置为可通过Javascript在整个域中访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想应该有一种方法来设置一个cookie,以便从整个域可以访问,从不设置从哪个目录cookie。

I suppose there should be a way to set a cookie to be accessible from the entire domain nevermind from which directory you are setting the cookie.

在mypage.com/blue/index.php中设置cookiecolor = blue;这样:

Say in mypage.com/blue/index.php y set the cookie "colour=blue;" this way:

document.cookie = "colour" + "=" + "blue" 
    + "; expires=" + expireDate.toGMTString() 
    + "; path=/";

使用此代码,mypage.com/home.php中的cookie检索功能无法访问cookie的内容。

Using this code, the cookie retrieval function in mypage.com/home.php can't access the content of the cookie.

如果只是从第一级目录,需要设置cookie,我们可以通过 path = .. / 而不是 path = /

If it was just from first level directories that the cookie needs to be set, we would be ok by doing path=../ instead of path=/

但是如何编写通用代码cookie可以从该域中的任何页面访问,但不知道该文件结构中的深度是设置cookie的页面。

But how do you go about writing generic code that sets a cookie that is accessible from any page in that domain not minding how deep in the file structure is the page the cookie is being set from?

推荐答案

使用 path 就像你所做的一样,但是设置了一个附加的-delimited属性domain。如果您以启动域值,它将允许任何子域( .example.com 有效地允许 *。example.com )。

Use path just like you did, but set an additional ;-delimited attribute "domain". If you start the domain value with a . it will allow any subdomains (.example.com would effectively allow *.example.com).

各种Cookie选项的完整文档此处

Full documentation for the various cookie options here

这篇关于如何将Cookie设置为可通过Javascript在整个域中访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆