Javascript - 使用Cookie存储整数 [英] Javascript - Using cookies to store an integer

查看:450
本文介绍了Javascript - 使用Cookie存储整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用cookie存储单个整数,因此当用户刷新页面时,我可以检索他们以前的号码(试图阻止出现视频的双击)。

I am trying to use a cookie to store a single integer, so when the user refreshes the page I am able to retrieve the previous number they were on (in an attempt to stop doubles of a video appearing).

最低要求是做什么的?

What would the minimum requirements be to accomplish this?

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

document.cookie=(randomNumber);

设定Cookie:

Setting a cookie:

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

读取cookie:

Reading a cookie:

var cookie = document.cookie;

alert(decodeURIComponent(cookie));

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

The cookie contains some other random stuff like push=1 as well as mycookie. Should I be setting the cookie to null before I add the randomNumber?

至于获取mycookie的值,我只需将cookie分配给一个字符串,然后将mycookie从它是什么?

As far as getting the value of mycookie would I just assign the cookie to a string and parse mycookie from it?

推荐答案

泰米尔的评论是可靠的。使用这些quirksmode功能,如果你想超越最小的cookie使用:

Tamil's comment is solid. Use these quirksmode functions if you ever wish to surpass minimal cookie usage:

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;
};

这篇关于Javascript - 使用Cookie存储整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆