結合JavaScript詳解Cookie
下方查看歷史精選文章
大數(shù)據(jù)測試過程、策略及挑戰(zhàn)
document.cookie=”userId=828″;document.cookie=”userId=828; userName=hulk”;document.cookie=”str=”+escape(”I love ajax”);document.cookie=”str=I%20love%20ajax”;document.cookie=”userId=828″;document.cookie=”userName=hulk”;
document.addCookie(”userId=828″);document.addCookie(”userName=hulk”);
document.cookie=”userId=929″;var strCookie=document.cookie;document.cookie=”userId=828; expires=GMT_String”;其中GMT_String是以GMT格式表示的時間字符串,這條語句就是將userId這個cookie設置為GMT_String表示的過期時間,超過這個時間,cookie將消失,不可訪問。
默認情況下,如果在某個頁面創(chuàng)建了一個cookie,那么該頁面所在目錄中的其他頁面也可以訪問該cookie。如果這個目錄下還有子目錄,則在子目錄中也可以訪問。例如在 www.xxxx.com/html/a.html 中所創(chuàng)建的cookie,可以被www.xxxx.com/html/b.html 或 www.xxx.com/html/ some/c.html 所訪問,但不能被 www.xxxx.com/d.html訪問。
document.cookie=”name=value; path=cookieDir”;document.cookie=”userId=320; path=/shop”;document.cookie=”userId=320; path=/”;document.cookie=”name=value; domain=cookieDomain”;document.cookie=”name=value;domain=.google.com”;cookie的處理過程比較復雜,并具有一定的相似性。因此可以定義幾個函數(shù)來完成cookie的通用操作,從而實現(xiàn)代碼的復用。下面列出了常用的cookie操作及其函數(shù)實現(xiàn)。
function SetCookie(name,value,expires,path,domain,secure){var expDays = expires*24*60*60*1000;var expDate = new Date();expDate.setTime(expDate.getTime()+expDays);var expString = ((expires==null) ? “” : (”;expires=”+expDate.toGMTString()))var pathString = ((path==null) ? “” : (”;path=”+path))var domainString = ((domain==null) ? “” : (”;domain=”+domain))var secureString = ((secure==true) ? “;secure” : “” )document.cookie = name + “=” + escape(value) + expString + pathString + domainString + secureString;}
2.獲取指定名稱的cookie值:
function GetCookie(name){var result = null;var myCookie = document.cookie + “;”;var searchName = name + “=”;var startOfCookie = myCookie.indexOf(searchName);var endOfCookie;if (startOfCookie != -1){startOfCookie += searchName.length;endOfCookie = myCookie.indexOf(”;”,startOfCookie);result = unescape(myCookie.substring(startOfCookie, endOfCookie));}return result;}
3.刪除指定名稱的cookie:
function ClearCookie(name){var ThreeDays=3*24*60*60*1000;var expDate = new Date();expDate.setTime(expDate.getTime()-ThreeDays);document.cookie=name+”=;expires=”+expDate.toGMTString();}
評論
圖片
表情


