【问题标题】:Not refreshing after setting cookie设置cookie后不刷新
【发布时间】:2012-01-25 18:22:23
【问题描述】:

我可以帮忙吗?使用 Javascript,我正在设置一个 cookie,然后刷新页面。我目前损坏的代码:

var username=getCookie("username");
if (username!=null && username!="")
{
    document.write("Welcome, " + username + "! <br/> <input type='button' value='Click to reset your name!' onclick='setCookie(\"username\",\"\",-1);' onmouseup='window.location.reload(true);'/>");
}
else
{
    username=prompt("Please enter your name:","Nothing is stored on the server.");
    if (username!=null && username!="")
    {
        setCookie("username",username,365);
    }
    window.location.reload(true);
}

获取 cookie:

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
  {
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

问题在于代码第一部分的 else{} 部分。提前致谢! :) 如果我的代码或其格式不正确,我深表歉意。 :(

【问题讨论】:

  • 刚刚格式化了您的代码。请编辑您的帖子以了解将来如何操作。
  • 是我,还是你克隆了w3schools.com/js/js_cookies.asp
  • 我将它用于我的代码,是的。但我正在尝试自动刷新,这就是这篇文章的目的。

标签: javascript cookies refresh


【解决方案1】:

请问可以看一下getCookie的定义吗?如果没有设置 cookie 会返回什么?

你看过 JS 错误控制台吗?

代码在下面重新格式化。

var username=getCookie("username");
if (username!=null && username!="")
{
    document.write("Welcome, " + username + "! <br/>
                    <input type='button' value='Click to reset your name!'             
                        onclick='setCookie(\"username\",\"\",-1);'
                        onmouseup='window.location.reload(true);'/>");
}
else
{
    username=prompt("Please enter your name:","Nothing is stored on the server.");
    if (username!=null && username!="")
    {
        setCookie("username",username,365);
    }
    window.location.reload(true);
}
// This last } is superfluous and may indicate issues with brackets
}

【讨论】:

  • 我已将 getCookie 包含在主帖中。
猜你喜欢
  • 2015-11-21
  • 1970-01-01
  • 2013-04-07
  • 1970-01-01
  • 2014-03-22
  • 2020-12-05
  • 2014-03-16
  • 2021-12-17
  • 1970-01-01
相关资源
最近更新 更多