javascript删除cookie在浏览器中的工作方式很奇怪
我正在尝试在javascript cookie上做一个演示测试。请查找下面我为测试编写的代码javascript删除cookie在浏览器中的工作方式很奇怪,javascript,cookies,Javascript,Cookies,我正在尝试在javascript cookie上做一个演示测试。请查找下面我为测试编写的代码 <html> <head> <script type='text/javascript' > function setcookie() { alert("check if cookie avail:" +document.cookie.split(';')); var dt=new Date(); document.cookie='n
<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>
函数setcookie()
{
警报(“检查cookie是否可用:+document.cookie.split(“;”));
var dt=新日期();
document.cookie='name=test';
document.cookie='expires='+dt.toutString()+';'
警报(“现在cookie val:+document.cookie.split(“;”);
dt.setDate(dt.getDate()-1);
document.cookie=“expires=“+dt.toutString()+”;”
警报(“删除后cookie val:+document.cookie.split(“;”));
}
代码的作用如下:
首先,这将显示浏览器中已经存在的cookie,然后我尝试将cookie设置为'name=test',并带有1天过期时间。使用alert,我可以看到该cookie中设置的值。在下一行中,我尝试通过将expire date设置为current date-1来删除cookie。如果我使用alert打印cookie值,则会显示cookie,过期日期为currentdate-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";
}
对不起,我不想要任何现有的代码。在这里,我试图通过做示例来自学javascript代码。我只是想知道为什么我的代码在不同浏览器之间不能正常工作。