0

我正在尝试对 javascript cookie 进行演示测试。请在下面找到我为测试编写的代码。

<html>
<head>
<script type='text/javascript' >

function setcookie()
{   
    alert("check if cookie avail:" +document.cookie.split(';'));
    var dt=new Date();

    document.cookie='name=test';
    document.cookie='expires='+dt.toUTCString()+';'
    alert("now cookie val:" +document.cookie.split(';'));

    dt.setDate(dt.getDate()-1);
    document.cookie = "expires=" + dt.toUTCString() + ";"
    alert("after deletion cookie val:" + document.cookie.split(';'));
 }
</script>

</head>
<body>
    <input id='txt' onchange='setcookie()' />
</body>
</html>

该代码将作为,

最初,这将显示该浏览器中已经存在的 cookie,然后我尝试将 cookie 设置为具有 1 天过期时间的“name=test”。使用警报我可以看到该 cookie 中设置的值。在下一行中,我尝试通过将过期日期设置为当前 date-1 来删除 cookie。如果我使用 alert 打印 cookie 值,cookie 将显示为 currentdate-1 的过期日期。

我的问题是,

  1. 在 Mozilla 中,如果我刷新浏览器并尝试执行相同的步骤,则第一个警报会显示 cookie 值,其过期时间为 currentdate-1。为什么即使我在脚本的最后一行删除,我也会获得 cookie 值。但是,一旦我关闭浏览器,cookie 值为空。为什么会这样?
  2. 在 chrome 中,如果我运行相同的代码,则不会设置任何 cookie。为什么我无法在 chrome 浏览器中设置 cookie。

请告诉我为什么跨浏览器会出现这种差异。

4

1 回答 1

1

这不是设置到期

document.cookie='name=test';
document.cookie='expires='+dt.toUTCString()+';'

这是

document.cookie='name=test; expires='+dt.toUTCString()+';'

最好的办法是采用经过良好测试的 cookie 代码并使用它

如果你使用 jQuery,试试这个或者使用 jQuery 插件

// cookie.js file
var daysToKeep = 14; // default cookie life...
var today      = new Date(); 
var expiryDate = new Date(today.getTime() + (daysToKeep * 86400000));


/* Cookie functions originally by Bill Dortsch */
function setCookie (name,value,expires,path,theDomain,secure) { 
   value = escape(value);
   var theCookie = name + "=" + value + 
   ((expires)    ? "; expires=" + expires.toGMTString() : "") + 
   ((path)       ? "; path="    + path   : "") + 
   ((theDomain)  ? "; domain="  + theDomain : "") + 
   ((secure)     ? "; secure"            : ""); 
   document.cookie = theCookie;
} 

function getCookie(Name) { 
   var search = Name + "=" 
   if (document.cookie.length > 0) { // if there are any cookies 
      var offset = document.cookie.indexOf(search) 
      if (offset != -1) { // if cookie exists 
         offset += search.length 
         // set index of beginning of value 
         var end = document.cookie.indexOf(";", offset) 
         // set index of end of cookie value 
         if (end == -1) end = document.cookie.length 
         return unescape(document.cookie.substring(offset, end)) 
      } 
   } 
} 
function delCookie(name,path,domain) {
   if (getCookie(name)) document.cookie = name + "=" +
      ((path)   ? ";path="   + path   : "") +
      ((domain) ? ";domain=" + domain : "") +
      ";expires=Thu, 01-Jan-70 00:00:01 GMT";
}
于 2013-02-02T08:28:49.143 回答