【问题标题】:jQuery Cookie default expiration datejQuery Cookie 默认过期日期
【发布时间】:2018-03-26 17:46:29
【问题描述】:

我正在使用 jQuery Cookie (https://github.com/carhartl/jquery-cookie) 来存储一些 cookie。

我希望此插件设置的所有 cookie 的默认到期日期为 365 天。我怎样才能做到这一点?

给这一行添加一个默认值:

config.defaults = {};

喜欢这个

config.defaults = {expires: 365};

不起作用。

这是插件:

/*!
 * jQuery Cookie Plugin v1.4.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2006, 2014 Klaus Hartl
 * Released under the MIT license
 */
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD (Register as an anonymous module)
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS
        module.exports = factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {

    var pluses = /\+/g;

    function encode(s) {
        return config.raw ? s : encodeURIComponent(s);
    }

    function decode(s) {
        return config.raw ? s : decodeURIComponent(s);
    }

    function stringifyCookieValue(value) {
        return encode(config.json ? JSON.stringify(value) : String(value));
    }

    function parseCookieValue(s) {
        if (s.indexOf('"') === 0) {
            // This is a quoted cookie as according to RFC2068, unescape...
            s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
        }

        try {
            // Replace server-side written pluses with spaces.
            // If we can't decode the cookie, ignore it, it's unusable.
            // If we can't parse the cookie, ignore it, it's unusable.
            s = decodeURIComponent(s.replace(pluses, ' '));
            return config.json ? JSON.parse(s) : s;
        } catch(e) {}
    }

    function read(s, converter) {
        var value = config.raw ? s : parseCookieValue(s);
        return $.isFunction(converter) ? converter(value) : value;
    }

    var config = $.cookie = function (key, value, options) {

        // Write

        if (arguments.length > 1 && !$.isFunction(value)) {
            options = $.extend({}, config.defaults, options);

            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setMilliseconds(t.getMilliseconds() + days * 864e+5);
            }

            return (document.cookie = [
                encode(key), '=', stringifyCookieValue(value),
                options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                options.path    ? '; path=' + options.path : '',
                options.domain  ? '; domain=' + options.domain : '',
                options.secure  ? '; secure' : ''
            ].join(''));
        }

        // Read

        var result = key ? undefined : {},
            // To prevent the for loop in the first place assign an empty array
            // in case there are no cookies at all. Also prevents odd result when
            // calling $.cookie().
            cookies = document.cookie ? document.cookie.split('; ') : [],
            i = 0,
            l = cookies.length;

        for (; i < l; i++) {
            var parts = cookies[i].split('='),
                name = decode(parts.shift()),
                cookie = parts.join('=');

            if (key === name) {
                // If second argument (value) is a function it's a converter...
                result = read(cookie, value);
                break;
            }

            // Prevent storing a cookie that we couldn't decode.
            if (!key && (cookie = read(cookie)) !== undefined) {
                result[name] = cookie;
            }
        }

        return result;
    };

    config.defaults = {};

    $.removeCookie = function (key, options) {
        // Must not alter options, thus extending a fresh object...
        $.cookie(key, '', $.extend({}, options, { expires: -1 }));
        return !$.cookie(key);
    };

}));

我将它与“Checkbox Cookie”jQuery 插件结合使用。这允许根据数据属性保存 cookie。让我更容易。但它无法保存到期日期。

这里有一个小提琴来看看它的实际效果: https://jsfiddle.net/2otL1gpf/5/

【问题讨论】:

  • 为什么不试试这样:$.cookie('name', 'value', { expires: 365 });?,正如您提供的链接中所建议的那样
  • 好吧,我正在使用上面的这个插件和另一个插件来根据选中的复选框设置 cookie。这个在这里:github.com/wellwind/cookie-checkbox,我不知道如何将它与您的解决方案结合起来。
  • 你是如何组合它们的,为什么你需要两者来处理 cookie?
  • 它允许通过在复选框上使用数据属性来使用 jQuery Cookie。一个非常简单的实现。我将多个复选框的状态存储在一个 cookie 中。这对我来说似乎是最简单的方法。我不是编码员,所以我想找到一个简单的解决方案。您可以在这里查看我正在尝试执行的操作:mydivision.net/the-division-gear-check cookie 运行良好,只是存储时间不超过会话。
  • 请在您的问题中发布一个小提琴或包含一个 sn-p,这样会容易得多,不过我会检查一下

标签: jquery cookies


【解决方案1】:

好的,我已经联系了原作者,这里有一个解决方案:

打开 Checkbox Cookie 脚本并替换第 6 行:

 $.cookie(cookieName, JSON.stringify(values)); 

 $.cookie(cookieName, JSON.stringify(values), { expires: 365 }); 

完成!

【讨论】:

    猜你喜欢
    • 2010-12-11
    • 1970-01-01
    • 2011-10-02
    • 2011-04-19
    • 1970-01-01
    • 2013-01-12
    • 2011-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多