如何设置两个 jquery cookie

How to setup two jquery cookies?

本文关键字:两个 jquery cookie 设置 何设置      更新时间:2023-09-26

我正在开发java ee应用程序,我有一个页面为不同的用户使用相同的cookie,这是不对的。所以我复制了 jquery.cookie.js 文件并创建了一个名为 jquery.cookie2.js 的新文件,我也更改了调用脚本,它有效,但它具有相同的操作。 无论我在旧用户中做什么,都会在新用户中发生。我认为这可能是cookie名称,所以我将其从

jQuery.cookie

jQuery.cookie2

在那之后它不起作用。这是饼干的代码

jQuery.cookie = function(name, value, options) {
if (typeof value != 'undefined') { // name and value given, set cookie
    options = options || {};
    if (value === null) {
        value = '';
        options.expires = -1;
    }
    var expires = '';
    if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
        var date;
        if (typeof options.expires == 'number') {
            date = new Date();
            date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
        } else {
            date = options.expires;
        }
        expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
    }
    // CAUTION: Needed to parenthesize options.path and options.domain
    // in the following expressions, otherwise they evaluate to undefined
    // in the packed version for some reason...
    var path = options.path ? '; path=' + (options.path) : '';
    var domain = options.domain ? '; domain=' + (options.domain) : '';
    var secure = options.secure ? '; secure' : '';
    document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
} else { // only name given, get cookie
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
};

我的问题是如何为一个应用程序使用不同的 cookie?

您刚刚复制并粘贴了 cookie 模块的源代码,这对您没有帮助。删除 jquery.cookie2.js。如果要使用两个不同的 Cookie,请设置两个不同 Cookie 的值:

//Set values
$.cookie('user1', 'firstValue');
$.cookie('user2', 'differentValue');
//Retrieve values
$.cookie('user1'); //Returns 'firstValue'
$.cookie('user2'); //Returns 'differentValue'

我不确定您是否需要使用cookie,特别是如果您的目标是在同一台机器/浏览器上的不同用户在客户端加载一些信息。有关使用localStorage的替代方法的详细信息,请参阅此答案,特别是如果您不需要在每次页面加载时将信息发送到服务器:https://stackoverflow.com/a/28253089/830125。