设置cookie后不刷新

时间:2011-12-22 01:03:11

标签: javascript cookies refresh

我可以帮忙吗?使用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 {}部分。提前致谢! :) 如果我的代码或格式不正确,我道歉。 :(

1 个答案:

答案 0 :(得分:0)

请问我们能看到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
}