【问题标题】:Javascript - Using cookies to store an integerJavascript - 使用 cookie 存储整数
【发布时间】:2012-06-30 16:58:15
【问题描述】:

我正在尝试使用 cookie 来存储单个整数,因此当用户刷新页面时,我能够检索他们之前所在的数字(以阻止出现双倍视频)。

要做到这一点,最低要求是什么?

var randomNumber = Math.floor((Math.random()*10)+1);

document.cookie=(randomNumber);

设置 cookie:

document.cookie = 'mycookie=' + randomNumber + ";max-age=" + (300) + ";";

读取 cookie:

var cookie = document.cookie;

alert(decodeURIComponent(cookie));

cookie 包含其他一些随机内容,例如 push=1 和 mycookie。我应该在添加 randomNumber 之前将 cookie 设置为 null 吗?

就获取 mycookie 的值而言,我只是将 cookie 分配给一个字符串并从中解析 mycookie 吗?

【问题讨论】:

标签: javascript html cookies


【解决方案1】:

泰米尔语的评论很中肯。如果您希望超过最小 cookie 使用量,请使用这些 quirksmode 函数:

cookie_create = function (name,value,days) {
    var expires, date;

    if (days) {
        date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires="+date.toGMTString();
    }
    else expires = "";
    document.cookie = name+"="+value+expires+"; path=/";

expires = date = null;
};


cookie_read = function (name) {
    var nameEQ = name + "=",
    ca = document.cookie.split(';'),
    len = ca.length,
    i, c; 

    for(i = 0; i < len; ++i) {
        c = ca[i];
        while (c.charAt(0) === ' ') c = c.substring(1); //,c.length);
        if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length); //,c.length);
    }

nameEQ = name = ca = i = c = len = null;
return null;
};


cookie_erase = function (name){
    cookie_create(name,"",-1);
name = null;
};

【讨论】:

    【解决方案2】:

    您可以使用document.cookie 在 javascript 中读取/写入 cookie:

    document.cookie = 'mycookie=' + randomNumber + '; path=/';
    

    如果您希望 cookie 即使在用户关闭浏览器后仍保持不变,您可以指定 expires 日期。

    【讨论】:

    • 非常感谢 :) 现在正在努力读取/解析 cookie:P
    猜你喜欢
    • 1970-01-01
    • 2012-05-31
    • 1970-01-01
    • 2011-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多