javascript jQuery cookie 过期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33232270/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:15:05  来源:igfitidea点击:

jQuery cookie expiry time

javascriptjquerycookies

提问by Ganga

I was able to set a cookie using jQuery with a redirect to a landing page but I have no idea how can I set the cookie expiry date to less then one day (for example 15 minutes). I was not able to find explanation in the plugin documentation

我能够使用 jQuery 设置 cookie 并重定向到登录页面,但我不知道如何将 cookie 到期日期设置为不到一天(例如 15 分钟)。我无法在插件文档中找到解释

Here is my code:

这是我的代码:

$(function() {
    var COOKIE_NAME = 'splash-page-cookie';
    $go = $.cookie(COOKIE_NAME);
    if ($go == null) {
        $.cookie(COOKIE_NAME, 'test', { path: '/', expires: 1 });
        window.location = "/example"
    }
    else {
        // do nothing
    }
});

Thank you for all help !

谢谢大家的帮助!

EDIT:I was able to set cookie as session cookie by skipping expire, well im fine with that but its not perfect, if you guys have some idea i would be grateful.

编辑:我能够通过跳过过期将 cookie 设置为会话 cookie,我对此很好,但它并不完美,如果你们有一些想法,我将不胜感激。

回答by adeneo

The plugins expiresoption accepts either a number or a date object.

pluginsexpires选项接受数字或日期对象。

If a number is passed, it's the number of days until the cookie expires, but if a date object is passed, it's the time and date when the cookie expires, so you can do

如果传递了一个数字,则它是距离 cookie 过期的天数,但如果传递了一个日期对象,则它是 cookie 过期的时间和日期,因此您可以这样做

var expDate = new Date();

expDate.setTime(expDate.getTime() + (15 * 60 * 1000)); // add 15 minutes

$.cookie(COOKIE_NAME, 'test', { path: '/', expires: expDate });

回答by Baconics

A fraction of a day should work, so for example there are 1440 minutes in a day so if you wanted the cookie to expire in 15 minutes you could simply divide the minutes by 1440 like so:

一天的一小部分应该可以工作,例如,一天有 1440 分钟,所以如果您希望 cookie 在 15 分钟后过期,您可以简单地将分钟除以 1440,如下所示:

$.cookie('foo', 'bar', {expires: 15/1440});

This would also work with hours, so for example if you wanted the cookie to expire in 2 hours you could do:

这也适用于数小时,因此例如,如果您希望 cookie 在 2 小时内过期,您可以执行以下操作:

$.cookie('foo', 'bar', {expires: 2/24});

A third option is to pass a date object like so:

第三种选择是传递一个日期对象,如下所示:

var expire = new Date();

//set expiry to current time plus 15 minutes in milliseconds
expire.setTime(expire.getTime() + (15 * 60 * 1000)); 

$.cookie('foo', 'bar', {expires: expire});

Hope this helps!

希望这可以帮助!