訪問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數據被刪除。
新聞熱點
疑難解答