使用javascript设置和检查cookie

问题描述:

我有一个脚本,在单击链接后设置cookie,然后当您再次访问该页面时,它将检查cookie并提醒您已经在这里。但是,我的代码似乎不工作。任何1可以帮助吗?使用javascript设置和检查cookie

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
 
"http://www.w3.org/TR/html4/loose.dtd"> 
 

 
<html> 
 

 
<head> 
 
    <title></title> 
 
    <script type="text/javascript"> 
 
     function get_cookie("visited"){ 
 
      if (document.cookie.indexOf("visited") >= 0) { 
 
       // They've been here before. 
 
       alert("hello again"); 
 
      } 
 
    </script> 
 

 
</head> 
 

 
<body onload="get_cookie()"> 
 

 
    <script type="text/javascript"> 
 
     /* This function sets the cookie */ 
 
     function iLoveCookies() { 
 
       days = 30; // number of days to keep the cookie 
 
       myDate = new Date(); 
 
       myDate.setTime(myDate.getTime() + (days * 24 * 60 * 60 * 1000)); 
 
       document.cookie = 'cookieName=visited; expires=' + myDate.toGMTString(); 
 
      } 
 
      /* end of cookie function */ 
 

 

 
     
 
    </script> 
 

 
    <a href="#" onclick="iLoveCookies()">Set Cookie</a> 
 
</body> 
 
</html>

+0

你缺少您的getCookie功能关闭}。 – 2015-04-03 18:19:07

+1

'function get_cookie(“visited”){}'无效。 – Dhiraj 2015-04-03 18:19:54

+0

我拿出了}但问题仍然存在。我如何检查我在这种情况下设置的Cookie。导致cookie正在设置,但没有正确检查 – Heli 2015-04-03 18:23:40

它看起来像你基本上有拼写错误造成的错误。您可能需要使用linter来检查您的JavaScript,或至少查看您的浏览器的developer console,看看它告诉你什么。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
 
"http://www.w3.org/TR/html4/loose.dtd"> 
 

 
<html> 
 

 
<head> 
 
    <title></title> 
 
    <script type="text/javascript"> 
 
     function get_cookie(){ 
 
      if (document.cookie.indexOf("visited") >= 0) { 
 
       // They've been here before. 
 
       alert("hello again"); 
 
      } 
 
      } 
 
    </script> 
 
    
 

 
</head> 
 

 
<body onload="get_cookie()"> 
 

 
    <script type="text/javascript"> 
 
     /* This function sets the cookie */ 
 
     function iLoveCookies() { 
 
       days = 30; // number of days to keep the cookie 
 
       myDate = new Date(); 
 
       myDate.setTime(myDate.getTime() + (days * 24 * 60 * 60 * 1000)); 
 
       document.cookie = 'cookieName=visited; expires=' + myDate.toGMTString(); 
 
      } 
 
      /* end of cookie function */ 
 
    </script> 
 

 
    <a href="#" onclick="iLoveCookies()">Set Cookie</a> 
 
    <a href="#" onclick="get_cookie()">Get Cookie</a> 
 
</body> 
 
</html>

+0

它现在的工作,谢谢 – Heli 2015-04-03 18:36:57

+0

很高兴听到它。仅供参考:您可以使用许多[现有库/框架](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie)。 – 2015-04-03 18:52:39