如何更新Cookie值(而不更改过期日期)? javascript [英] How to update a cookie value (and not change the expire date)? javascript

查看:802
本文介绍了如何更新Cookie值(而不更改过期日期)? javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要执行的下一个代码:

I have next code where I do:

检查我的cookie是否存在(如果不存在),然后在其中读取我创建的名为value
的cookie再次检查cookie并检查其值是否为1,在此我想设置一个新值,但不更改此cookie的过期日期和时间,只会更新该值

Check if my cookie exist if it not exist then I create the cookie called value inside else I read the cookie again and check if value is 1, here i would like to set a new value but not change the expire date and time of this cookie only update the value

if( readCookie("value")==null)
{

createCookie("value",1,1);
}
else
{
if(readCookie("value")==1)
{
/*here I would like to set to cookie called value the new value to 2 */
}
else
{
alert("no es uno");
}
}

function createCookie(name, value, days) {
    var expires;

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

function readCookie(name) {
    var nameEQ = encodeURIComponent(name) + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}


推荐答案

而您不能直接检查有效期,设置cookie时可以将有效期存储为cookie的一部分。然后,每当要检查到期日期时,您都可以查看Cookie的该部分。并且要更改cookie而又不影响有效期,只需重新创建cookie,替换有效期即可。

While you can't directly check the expiry date, when you set the cookie up you can store the expiry date as part of the cookie. Then whenever you want to check the expiry date, you can look at that part of the cookie. And to change the cookie without affecting the expiry date, just recreate the cookie, replacing the expiry date.

document.cookie="username=John Doe Thu, 18 Dec 2013 12:00:00 UTC; expires=Thu, 18 Dec 2013 12:00:00 UTC";

您始终可以在创建Cookie时更改其失效日期。

You can always change the expiry date of the cookie when it is being created.

这篇关于如何更新Cookie值(而不更改过期日期)? javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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