开发者

How can I get and set cookies using JavaScript? [duplicate]

This question already has answers here: What is the "best" way to get and set a single cookie value using JavaScript (3 answers) Closed 9 years ago.

I am trying to implement cookies on a webpage. I开发者_高级运维 am having trouble getting it to function properly. I am wanting to store the value of some variables as well. I realize this is very broad, but I know little to nothing about JavaScript cookies and I am working off the w3schools examples. This is what I have so far:

var days=365;
function setCookie(child,user,days) {
var exdate=new Date();
exdate.setDate(exdate.getDate() + days);
var child=escape(user) + ((365==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=child + "=" + child;
}

function getCookie(child) {
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==child) {
    return unescape(y);
    }
  }
}

function checkCookie() {
var username=getCookie("username");
  if (username!=null && username!="") {
  alert("Welcome again " + username);
  } else {
  username=prompt("Please enter your name:","");
  if (username!=null && username!="") {
    setCookie("username",username,days);
    }
  }
}


Yes, you have a parse error on line 1. As Matt said, "365" is not legal here.

Also, it looks like this code will never evaluate to true...

if (x==child)
    {
    return unescape(y);
    }
  }

...and so the cookie value y will never be returned.

There are other things that look problematic in your code too, but I would start with what I've mentioned here. Also, try debugging with some JavaScript tools, ie. Firebug.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜