Javascript - 存储后Cookie值会发生变化

时间:2013-05-05 16:42:06

标签: javascript html html5 cookies

我有这个代码来设置cookie:

function SetCookie(cookieName, cookieValue, nDays) {
    var today = new Date();
    var expire = new Date();
    if (nDays == null || nDays == 0) nDays = 1;
    expire.setTime(today.getTime() + 3600000 * 24 * nDays);
    document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" + expire.toGMTString(), ';path = /';
}

设置cookie我必须用所有参数调用函数。

SetCookie("number", "1", 10);

但是当我使用我的ReadCookie函数获取值时,cookie值不是1:

function ReadCookie(cookieName) {
    var theCookie = "" + document.cookie;
    var ind = theCookie.indexOf(cookieName + "=");
    if (ind == -1 || cookieName == "") return "";
    var ind1 = theCookie.indexOf(";", ind);
    if (ind1 == -1) ind1 = theCookie.length;
    return unescape(theCookie.substring(ind + cookieName.length + 1, ind1));
}

输出而不是“1”是:

e85751a63874d221ff23323575137233

1 个答案:

答案 0 :(得分:0)

您的代码似乎工作正常,但我想我会发布一些代码来编写代码以通过JavaScript处理Cookie,以便为您提供有关您可以执行的操作的更多信息。我基于MDN示例here,但具有我想要的功能(对象查找,缓存直到更改)。随意为您的项目提升代码(或全部使用)。

cookie.setItem('number', 1, 10 * 24 * 60 * 60); // expires is Number => seconds
cookie.getItem('number'); // "1"

function cookie使 String 格式正确,以便与document.cookie一起使用,它需要参数 key,val,expires,path ,域名,安全。参数 expires 可以是 Number (从现在起的秒数或 Infinity ), Date String

功能 cookie.setItem具有与cookie相同的参数,但也适用它。如果只给出,则假定它是一个完整的cookie格式的 String

功能 cookie.getItem只接受参数。

功能 cookie.removeItem包含参数键,路径。您只需要使用

var cookie = (function () {
    var cookieString = '',
        items = {},
        expireNever = new Date(new Date().valueOf() + 64e10).toGMTString(), // 20 years
        expireNow = 'Thu, 01 Jan 1970 00:00:00 GMT',
        cookie,
        __update,
        supportsMaxAge = 1;
    __update = function () {
        var a, i, j, o = {};
        cookieString = document.cookie;
        a = cookieString.split('; ');
        i = a.length;
        while (i--) {
            j = a[i].indexOf('=');
            o[decodeURIComponent(a[i].slice(0, j))]
                = decodeURIComponent(a[i].slice(j + 1));
        }
        items = o;
    }
    cookie = function cookie(key, val, expires, path, domain, secure) {
        var s = encodeURIComponent(''+key) + '='
              + encodeURIComponent(''+val);
        if (!key) return '';
        if (expires || expires === 0) {
            switch (expires.constructor) {
                case Number:
                    if (expires === Infinity) expires = 'expires=' + expireNever;
                    else {
                        if (supportsMaxAge) expires = 'max-age=' + expires;
                        else expires = 'expires=' + new Date(new Date().valueOf() + expires * 1000).toGMTString();
                    }
                    break;
                case Date:
                    expires = 'expires=' + expires.toGMTString();
                    break;
                default:
                case String:
                    expires = 'expires=' + expires;
                    break;
            }
            s = s + '; ' + expires;
        }
        if (domain) s = s + '; domain=' + domain;
        if (path) s = s + '; path=' + path;
        if (secure) s = s + '; secure';
        return s;
    };
    cookie.getNames = function () {
        if (document.cookie !== cookieString) __update();
        return Object.keys(items);
    };
    cookie.getItem = function (key) {
        var s;
        if (document.cookie !== cookieString) __update();
        s = items[key];
        if (s || s === '') return s;
        return null;
    };
    cookie.setItem = function (key, val, expires, path, domain, secure) {
        var s;
        if (!key) return null;
        if (val === void 0) s = key;
        else s = cookie(key, val, expires, path, domain, secure);
        document.cookie = s;
        return s;
    };
    cookie.hasItem = function (key) {
        if (cookie.getItem(key) === null) return false;
        return true;
    };
    cookie.removeItem = function (key, path) {
        if (cookie.setItem(key, '', expireNow, path)) return true;
        return false;
    };
    // find out if max-age is supported
    cookie.setItem('test_cookie_max_age', '1', 0);
    if (cookie.getItem('test_cookie_max_age')) {
        supportsMaxAge = 0;
        cookie.removeItem('test_cookie_max_age');
    }
    __update();
    return cookie;
}());