jQuery 如何设置此cookie永不过期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10641737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to set this cookie to never expire
提问by John mido
I have a function to create a cookie passing in the name, value and expiration (in days) of the cookie.
我有一个函数来创建一个传递 cookie 的名称、值和到期时间(以天为单位)的 cookie。
Here is the function:
这是函数:
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);
}
}
}
The function works as expected, but what do I need to do to set the cookie never expire?
该功能按预期工作,但我需要做什么才能设置 cookie 永不过期?
回答by Prasenjit Kumar Nag
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.
没有办法设置为never expire
。这不是 javascript 限制,它只是不是 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
您可以设置为将来的一个较远日期。例如,从现在起将其设置为 20 年,setCookie
使用20*365
作为exdays
参数调用,因为您setCookie
期望它在到期前的天数。喜欢如下
setCookie('cookiename','cookie_val',20*365);
回答by adeneo
The variable exdays
is how long it is until the cookie expires, just set that value to a couple of thousand days in your function call.
变量exdays
是 cookie 过期的时间,只需在函数调用中将该值设置为几千天。
setCookie('cookiename', 'cookievalue', 10000); //expires in 10k days