當(dāng)前位置:軟件學(xué)堂 > 資訊首頁 > 網(wǎng)絡(luò)編程 > 編程其他 > 讀寫Cookie的函數(shù)JS代碼怎么寫

讀寫Cookie的函數(shù)JS代碼怎么寫

2012/11/6 17:22:38作者:佚名來源:網(wǎng)絡(luò)

移動(dòng)端

【實(shí)例名稱】

讀寫Cookie的函數(shù)JS代碼怎么寫

【實(shí)例描述】

cookie是客戶端用來保存數(shù)據(jù)的對象,本例將所有有關(guān)Cookie的操作封裝成一個(gè)函數(shù)庫。讀者通過學(xué)習(xí)本例可以全面地掌握Cookie的使用。

【實(shí)例代碼】

<html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>標(biāo)題頁-學(xué)無憂(www.denvermotorcycleaccidentlawyer.com)</title> <script Language="JavaScript"> //獲得Cookie解碼后的值 function GetCookieVal(offset) { var endstr = document.cookie.indexOf (";", offset); if (endstr == -1) endstr = document.cookie.length; return unescape(document.cookie.substring(offset, endstr)); } //設(shè)定Cookie值-將值保存在Cookie中 function SetCookie(name, value) { var expdate = new Date();                      //獲取當(dāng)前日期 var argv = SetCookie.arguments;                //獲取cookie的參數(shù) var argc = SetCookie.arguments.length;         //cookie的長度 var expires = (argc > 2) ? argv[2] : null;     //cookie有效期 var path = (argc > 3) ? argv[3] : null;        //cookie路徑 var domain = (argc > 4) ? argv[4] : null;      //cookie所在的應(yīng)用程序域 var secure = (argc > 5) ? argv[5] : false;     //cookie的加密安全設(shè)置 if(expires!=null) expdate.setTime(expdate.getTime() + ( expires * 1000 )); document.cookie = name + "=" + escape (value) +((expires == null) ? "" : ("; expires="+ expdate.toGMTString())) +((path == null) ? "" : ("; path=" + path)) + ((domain == null) ? "" : ("; domain=" + domain)) +((secure == true) ? "; secure" : ""); } //刪除指定的Cookie function DelCookie(name) { var exp = new Date(); exp.setTime (exp.getTime() - 1); var cval = GetCookie (name); //獲取當(dāng)前cookie的值 document.cookie = name + "=" + cval + "; expires="+ exp.toGMTString(); //將日期設(shè)置為過期時(shí)間 } //獲得Cookie的值-name用來搜索Cookie的名字 function GetCookie(name) { var arg = name + "="; var argLen= arg.length;                  //指定Cookie名的長度 var cookieLen= document.cookie.length;   //獲取cookie的長度 var i = 0; while (i < cookieLen) {     var j = i + argLen;     if (document.cookie.substring(i, j) == arg) //依次查找對應(yīng)cookie名的值     return GetCookieVal (j);     i = document.cookie.indexOf(" ", i) + 1;     if (i == 0) break; } return null; } </script> </head> <body> <input type=text name="txt1" value="搜索引擎是百度"> <input type=button value="保存Cookie" onClick="javascript:SetCookie('sousuo', txt1.value)"> <input type=button value="獲取Cookie" onClick=" javascript:alert(GetCookie('sousuo'))"> </body> </html>

【運(yùn)行效果】

 讀寫Cookie的函數(shù)運(yùn)行效果

【難點(diǎn)剖析】

本例的重點(diǎn)是“document.cookie”,在JavaScript中不管是保存Cookie還是獲取Cookie,都是使用“document.cookie”。具體的使用方法參考代碼中的注釋。

【源碼下載】

為了JS代碼的準(zhǔn)確性,請點(diǎn)擊:讀寫Cookie的函數(shù) 進(jìn)行本實(shí)例源碼下載 

標(biāo)簽: Cookie  函數(shù)  JS代碼