22

我有一个函数来创建一个 cookie,传递 cookie 的名称、值和到期时间(以天为单位)。

这是功能:

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

该功能按预期工作,但我需要做什么才能设置 cookie 永不过期?

4

2 回答 2

34

There is no way to set to never expire . It's not a javascript limitation, it's just not the part of the specification of the cookie http://www.faqs.org/rfcs/rfc2965.html.

You can set to a far date in the future. for example to set it for 20years from now call setCookie with 20*365 as exdays parameter as you setCookie function expect how many days before it expires. Like follows

setCookie('cookiename','cookie_val',20*365);
于 2012-05-17T18:56:38.123 回答
12

变量exdays是 cookie 过期的时间,只需在函数调用中将该值设置为几千天。

setCookie('cookiename', 'cookievalue', 10000); //expires in 10k days
于 2012-05-17T18:49:49.540 回答