2015-05-13 195 views
1

我喜欢网站,当用户登录并检查“记住我”时,我写入cookie用户名。它运行良好,但只是在某些浏览器中。 我写在cookie中的代码名:IE浏览器在关闭浏览器后做注销

document.cookie = ""; 
    document.cookie = "username=" + username; 

并登录后我检查用户名从饼干。 但在IE浏览器中它不起作用。 关闭浏览器并再次打开他的cookies后清除。 为什么它会发生? 以及如何解决它?

+1

可能的重复[如何创建和从cookie读取值?](http://stackoverflow.com/questions/4825683/how-do-i-create-and-read-a-value-from- cookie) –

回答

1

我发现的get/set饼干好的代码:

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 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); 
     } 
    } 
    } 

来源:How do I create and read a value from cookie?

感谢您heru-luin

1

看到官方的MS开发者网络文档 - >https://msdn.microsoft.com/en-us/library/ms533693%28v=vs.85%29.aspx

如果设置没有到期日上的cookie,当浏览器关闭 到期。如果您设置了到期日期,则cookie会保存在浏览器会话中的 之间。如果您过去设置了到期日期,则会删除 Cookie。使用格林威治标准时间(格林尼治标准时间)格式来指定 日期。

所以你基本上需要指定一个过期日期,如果你想cookie保存在IE中。从上面的链接示例:

// Create a cookie with the specified name and value. 
function SetCookie(sName, sValue) 
{ 
    document.cookie = sName + "=" + escape(sValue); 
    // Expires the cookie in one month 
    var date = new Date(); 
    date.setMonth(date.getMonth()+1); 
    document.cookie += ("; expires=" + date.toUTCString()); 
} 

或看到这个优秀的答案 - >Using javascript to set cookie in IE

+0

谢谢。这是非常有用的答案。 –