如何用JavaScript处理cookie? [英] How to handle cookies in JavaScript?
问题描述
我正在一个项目中工作,它需要检查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屋!