检查Cookie是否存在,否则设置Cookie以在10天后过期 [英] Check if cookie exists else set cookie to Expire in 10 days

查看:190
本文介绍了检查Cookie是否存在,否则设置Cookie以在10天后过期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是我要查找的(伪代码):

Here is what I'm looking to do (pseudo-code):

想象一下,在示例中的cookie的名称是visited 。

Imagine the name of the cookie in the example is "visited" and it contains nothing.

if visited exists
then alert("hello again");
else
create visited - should expire in 10 days;
alert("This is your first time!")

JavaScript

How can I achieve this in JavaScript?

推荐答案

您需要读写 document.cookie / p>

You need to read and write document.cookie

if (document.cookie.indexOf("visited") >= 0) {
  // They've been here before.
  alert("hello again");
}
else {
  // set a new cookie
  expiry = new Date();
  expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes

  // Date()'s toGMTSting() method will format the date correctly for a cookie
  document.cookie = "visited=yes; expires=" + expiry.toGMTString();
  alert("this is your first time");
}

这篇关于检查Cookie是否存在,否则设置Cookie以在10天后过期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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