【问题标题】:Setting a Site Wide Cookie设置站点范围的 Cookie
【发布时间】:2012-02-19 14:30:54
【问题描述】:

我希望这是一个快速的问题...

我正在尝试设置一个可在站点范围内使用的 cookie。我正在创建一个潜在客户生成类型的网站。我希望用户填写表格以访问独家信息。一旦他们填写了表格,他们就可以访问信息。

当他们的用户提交表单时,我会删除一个 cookie,以便他们下次访问该网站时可以直接访问内容。他们填写的表格位于网站每个页面的侧边栏中。当用户在一个页面上填写表单时,他们不应该在网站的任何页面上看到它。

一切正常,除了全站位。我认为问题在于这段代码:

function set_cookie(name, value, expires, path, domain, secure){
if (!expires){expires = new Date()}
document.cookie = name + "=" + escape(value) + 
((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
((path == null) ? "" : "; path=" + path) +
((domain == null) ? "" : "; domain=" + domain) +
((secure == null) ? "" : "; secure");
}

但下面是完整的代码。非常感谢!

<script type="text/javascript">
<!--
cookie_name="landasp"
expdays=365

// An adaptation of Dorcht's cookie functions.

function set_cookie(name, value, expires, path, domain, secure){
if (!expires){expires = new Date()}
document.cookie = name + "=" + escape(value) + 
((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
((path == null) ? "" : "; path=" + path) +
((domain == null) ? "" : "; domain=" + domain) +
((secure == null) ? "" : "; secure");
}

function get_cookie(name) {
var arg = name + "=";
var alen = arg.length; 
var clen = document.cookie.length;
var i = 0; 
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg){
return get_cookie_val(j); 
}
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}

function get_cookie_val(offset){
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}

function delete_cookie(name,path,domain){
document.cookie = name + "=" +
((path == null) ? "" : "; path=" + path) +
((domain == null) ? "" : "; domain=" + domain) +
"; expires=Thu, 01-Jan-00 00:00:01 GMT";
}

function saving_cookie(){
var expdate = new Date ();
expdate.setTime (expdate.getTime() + (expdays*24*60*60*1000*30)); //set for one month
Data="cooked"

set_cookie(cookie_name,Data,expdate)
}

function get_cookie_data(){
inf=get_cookie(cookie_name)
if(!inf){
document.getElementById("display1").style.display="block"
}
else{
document.getElementById("display2").style.display="block"
}
}

// -->
</script> 

【问题讨论】:

  • 欢迎来到stackoverflow!如果您认为某个答案回答了您的问题,请点击绿色复选框将其标记为已回答。

标签: javascript cookies setcookie


【解决方案1】:

如果没有给出路径,你应该指定一个站点范围的路径:

((path == null) ? "; path=/" : "; path=" + path) +

您可以使用 Firebug 调试 cookie,只需查看设置的 cookie。

【讨论】:

  • 非常感谢!我一直在绞尽脑汁试图做到这一点!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-07
  • 1970-01-01
  • 2020-02-21
  • 2020-12-18
  • 1970-01-01
相关资源
最近更新 更多