开发者

javascript cookies

开发者 https://www.devze.com 2023-02-20 13:04 出处:网络
can anyone tell me开发者_运维知识库 about automatic cookies in JavaScript while clicking a button or URL of a webpage?

can anyone tell me开发者_运维知识库 about automatic cookies in JavaScript while clicking a button or URL of a webpage? It sets for me and I can't delete that also...


 var expDate = new Date();
 expDate.setYear( parseInt(expDate.getYear())+10);
 document.cookie="";
var x = "$user=$val; expires="+expDate.toUTCString();

Here i have two buttons called 'view' and 'save'. If i click the 'save' button this cookie should be set... but when i click the 'view' button a cookie is set. i cant delete tht cookie too


I find the method explained in this article at quirksmode.org to be working just fine. —  Mabye give that a try?


Best code to understand cookie in javascript

Just save my code as html file and open into browser you willeasily understand cookie concept

<!DOCTYPE html>
<html>
<head>
<script>
function getCookie(c_name)
 {
   var c_value = document.cookie;
   var c_start = c_value.indexOf(" " + c_name + "=");
   if (c_start == -1)
    {
      c_start = c_value.indexOf(c_name + "=");
    }
 if (c_start == -1)
   {
     c_value = null;
   }
 else
  {
    c_start = c_value.indexOf("=", c_start) + 1;
    var c_end = c_value.indexOf(";", c_start);
   if (c_end == -1)
     {
      c_end = c_value.length;
      }
   c_value = unescape(c_value.substring(c_start,c_end));
   }
  return c_value;
  }

 function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

 function checkCookie()
{
var username=getCookie("username");
if (username!=null && username!="")
  {
  alert("Welcome again " + username);
  }
else 
  {
  username=prompt("Please enter your name:","");
  if (username!=null && username!="")
    {
    setCookie("username",username,365);
    }
  }
 }
</script>
</head>
<body onload="checkCookie()">
</body>

0

精彩评论

暂无评论...
验证码 换一张
取 消