2012-03-02 154 views
0

当用户输入值到文本框中时,Cookie被设置。为什么页面刷新后cookie丢失

但是,页面刷新后Cookie丢失。

下面是我的代码,任何人都可以帮助我吗?非常感谢!

<script type="text/javascript"> 
    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); 
     } 
     } 
    } 

    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 emailVal=getCookie("email"); 
    if (emailVal!=null && emailVal!="") 
     { 
     document.getElementById('emailBox').value =emailVal; 
     } 
    else 
     { 
     var eVal = document.getElementById('emailBox').value; 

     setCookie("email",eVal,365); 

     } 
    } 
    </script> 

    <body> 
    <form> 

    <input type="text" id="emailBox" name="email" onchange="checkCookie()"/> 

    </form> 
    </body> 

回答

1

对我的作品在这里很好 - >http://jsfiddle.net/RAZZg/1/

,我认为可能是错的唯一的事情就是你的JavaScript代码放置...试着将它要么<body>标签内或添加<head>标签:

<head> 
// your code here 
</head> 
<body onload="checkCookie()"> 
</body> 

更新:加入onload属性body标签,以检查在页面加载cookie的

+0

刷新后文本框中没有值 – Acubi 2012-03-02 11:39:30

+0

仅当您更改值时才会更改该值 - 即“checkCookie”函数被称为“onchange”...如果要在加载时检查cookie,请使用'body.onload '事件 – ManseUK 2012-03-02 11:40:54

+0

你是对的@ManseUK。如果我想在刷新后让cookie值保留在文本框中,我应该做什么更改? – Acubi 2012-03-02 11:44:32