前端js cookie的使用
cookie的作用:服務(wù)器可以利用Cookies包含信息的任意性來篩選并經(jīng)常性維護這些信息,以判斷在HTTP傳輸中的狀態(tài)。Cookies最典型的應(yīng)用是判定注冊用戶是否已 經(jīng)登錄網(wǎng)站,用戶可能會得到提示,是否在下一次進入此網(wǎng)站時保留用戶信息以便簡化登錄手續(xù),這些都是Cookies的功用。另一個重要應(yīng)用場合是“購物 車”之類處理。用戶可能會在一段時間內(nèi)在同一家網(wǎng)站的不同頁面中選擇不同的商品,這些信息都會寫入Cookies,以便在最后付款時提取信息。
js設(shè)置cookie
document.cookie="popped=yes"
js獲取cookie
function get_cookie(Name) { var search = Name + "="http://查詢檢索的值 var returnvalue = "";//返回值 if (document.cookie.length > 0) { sd = document.cookie.indexOf(search); if (sd!= -1) { sd += search.length; end = document.cookie.indexOf(";", sd); if (end == -1) end = document.cookie.length; //unescape() 函數(shù)可對通過 escape() 編碼的字符串進行解碼。 returnvalue=unescape(document.cookie.substring(sd, end)) } } return returnvalue;}//使用方式:get_cookie("popped");
給cookie設(shè)置終止日期
例如:如果要將cookie設(shè)置為10天后過期,可以這樣實現(xiàn):
//獲取當前時間var date=new Date();var expiresDays=10;//將date設(shè)置為10天以后的時間date.setTime(date.getTime()+expiresDays*24*3600*1000);//將userId和userName兩個cookie設(shè)置為10天后過期document.cookie="userId=828; userName=hulk; expires="+date.toGMTString();
刪除cookie
為了刪除一個cookie,可以將其過期時間設(shè)定為一個過去的時間,例如:
//獲取當前時間var date=new Date();//將date設(shè)置為過去的時間date.setTime(date.getTime()-10000);//將userId這個cookie刪除document.cookie="userId=828; expires="+date.toGMTString();
下面封裝上面的方法
var cookie = { set:function(key,val,time){//設(shè)置cookie方法 var date=new Date(); //獲取當前時間 var expiresDays=time; //將date設(shè)置為n天以后的時間 date.setTime(date.getTime()+expiresDays*24*3600*1000); //格式化為cookie識別的時間 document.cookie=key + "=" + val +";expires="+date.toGMTString(); //設(shè)置cookie }, get:function(key){//獲取cookie方法 /*獲取cookie參數(shù)*/ var getCookie = document.cookie.replace(/[ ]/g,""); //獲取cookie,并且將獲得的cookie格式化,去掉空格字符 var arrCookie = getCookie.split(";") //將獲得的cookie以"分號"為標識 將cookie保存到arrCookie的數(shù)組中 var tips; //聲明變量tips for(var i=0;i<arrCookie.length;i++){ //使用for循環(huán)查找cookie中的tips變量 var arr=arrCookie[i].split("="); //將單條cookie用"等號"為標識,將單條cookie保存為arr數(shù)組 if(key==arr[0]){ //匹配變量名稱,其中arr[0]是指的cookie名稱,如果該條變量為tips則執(zhí)行判斷語句中的賦值操作 tips=arr[1]; //將cookie的值賦給變量tips break; //終止for循環(huán)遍歷 } }, delete:function(key){ //刪除cookie方法 var date = new Date(); //獲取當前時間 date.setTime(date.getTime()-10000); //將date設(shè)置為過去的時間 document.cookie = key + "=v; expires =" +date.toGMTString();//設(shè)置cookie } return tips; }}
使用方式:
cookie.set("uesr","sss",24);//設(shè)置為24天過期alert(cookie.get("uesr"));//獲取cookie
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持武林網(wǎng)!
新聞熱點
疑難解答