访问cookie数据非常简单,都是通过document.cookie来实现的:
(1)存储:document.cookie = strCookie
(2)读取:strCookie = document.cookie
下面的代码只能在IE浏览器运行,因为IE浏览器允许本地文件设置cookie数据,而Chrome浏览器不支持本地文件访问cookie,把代码嵌入在网站代码内,验证通过,且一直能保存这个cookie数据,直到过期为止。
代码:
<!doctype html><html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <!--script src="cookieLib.js"></script>--> <script language="javascript"> function saveCookie(name,value,expires,path,domain,secure) { var strCookie = name + "=" + value + ";"; if(expires) //有效期 { var c = new Date(); c.setTime(c.getTime() + expires * 24 * 60 * 60 * 1000); strCookie += "expires=" + c.toGMTString() + ";"; } strCookie += (domain) ? "domain="+domain +";": ""; //web网域名称,用来分辨是哪个网站创建的 strCookie += (path) ? "path="+path+";" : ""; //domain属性下的路径,进一步区分是哪个网页创建的 strCookie += (secure) ? "secure="+secure +";" : "";//cookie需要在保密情况下,才能在客户端服务器直接发送 document.cookie = strCookie; } function getCookie(name) { var strCookie = document.cookie; var s = strCookie.indexOf(name); if(s != -1) { var e = strCookie.indexOf(";"); //把等于号之后的数据返回 return (e == -1) ? strCookie.substring(s+name.length+1,strCookie.length) : strCookie.substring(s+name.length+1,e); } else return null; } function checkCookieExist(name) { return (getCookie(name) == null) ? false : true; } function deleteCookie(name,path,domain) { var strCookie; if(checkCookieExist(name)) { strCookie = name + "=;"; strCookie += (domain) ? "domain="+domain+";" : ""; strCookie += (path) ? "path="+path+";" : ""; strCookie += "expires=Thu,01-Jan-70 00:00:01 GMT;"; } document.cookie = strCookie; } function hitCounter() { var counter; if(checkCookieExist("counter")) { counter = getCookie("counter"); //自增1; counter = parseInt(counter) + 1; } else { counter = 1; } saveCookie("counter",counter,10); return counter; } </script> </head> <body> <h1><center> <script language="Javascript"> document.write("访问网页次数:" + hitCounter()+"次"); </script> </center> </h1> <input type="button" value="重新加载网页" onclick="location.reload();"> </body></html>效果是 每次点击 重新加载网页,或者刷新,计数都会自增1,打开多次网页,可以共享同一个cookie数据:这个cookie数据,在我电脑上的这个目录下C:/Users/Administrator/AppData/Local/Microsoft/Windows/Temporary Internet Files,文件名为Desktop/ ,内容如下:
这个cookie数据实际上是存储在这个目录下的:C:/Users/Administrator/AppData/Roaming/Microsoft/Windows/Cookies。
在关闭网页之后,cookie数据被删除。
新闻热点
疑难解答