如何用JavaScript处理cookie? [英] How to handle cookies in JavaScript?

查看:96
本文介绍了如何用JavaScript处理cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

我正在一个项目中工作,它需要检查cookie并告诉它是否是20分钟老。所以我已经写了一次这样的代码。
这是我粘贴的JavaScript代码。

I am working on a project where it requires to check cookie and tell whether it is 20 minutes old or not. So I have written once code which is like this. This is only javascript code I have pasted.

function checkcookie()
{
    var difftime= getcookie();
    // further operation comes here
}

var cookieminutes;

function getcookie()
{
    var start = document.cookie.indexOf("expires");
    var cookiedate;

    if(start==-1)
    {
        cookiedate = new Date();
        document.write("Start equal to -1");
        document.cookie="expires="+cookiedate+",path=0,domain=0";
        cookieminutes= cookiedate.getMinutes();
    }
    else
    {
        document.write("Start not equal to -1");

        var date =  new Date();
        var minutes = date.getMinutes();

        document.write("The difference is "+minutes);
        document.write("<br />Cookie minutes is "+cookieminutes);
        return (minutes-cookieminutes);

    }
}

在函数getcookie中,变量cookieminutes是未定义。但是,我知道,因为它是一个全局变量,它应该有值。

In function getcookie the variable cookieminutes is coming as undefined. But as I know since it is a global variable it should have the value.

任何人都可以告诉这是什么解决方案。

Can anybody please tell what is the solution for this.?

推荐答案

您只在if语句的顶部设置了cookieminutes的值,因此else部分中的任何引用都将为null。

You're only setting a value for cookieminutes in the top section of the if statement, so any references in the else section will be null.

试试这个:

function getcookie()
{
    var start = document.cookie.indexOf("expires");
    var cookiedate;

    cookiedate = new Date();
    cookieminutes = cookiedate.getMinutes();

    if(start==-1)
    {    
        document.write("Start equal to -1");
        document.cookie="expires="+cookiedate+",path=0,domain=0";    
    }
    else
    {
        document.write("Start not equal to -1");

        var date =  new Date();
        var minutes = date.getMinutes();

        document.write("The difference is "+minutes);
        document.write("<br />Cookie minutes is "+cookieminutes);
        return (minutes-cookieminutes);

    }
}

这篇关于如何用JavaScript处理cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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