我正在尝试在 javascript 中创建然后检索 cookie。我使用的是谷歌浏览器,当我运行下面的代码时,它不会在页面重新加载后存储 cookie。
下面是我的代码
<html>
<title> Cookies </title>
<body onload="checkCookie()">
<script type="text/javascript">
function getCookie(c_name){
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1){
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1){
c_value = null;
}else{
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c.value.indexOf(";", c_start);
if (c_end ==-1){
c_end = c_value.lenth;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
}
function setCookie(c_name,value,exdays){
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
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,365);
document.write(username);
}
}
}
</script>
<body>
我不知道为什么它不起作用,我从这里复制/粘贴它http://www.w3schools.com/js/js_cookies.asp