cookie的優(yōu)勢能夠與服務器共享狀態(tài),每次通過ajax請求的時候都會將cookie附帶到請求的header,服務端能夠直接讀取到本地存儲的數(shù)據(jù)。
GET /sample_page.html HTTP/1.1 Host: www.example.org Cookie: yummy_cookie=choco; tasty_cookie=strawberry
瀏覽器限制情況
cookie在chrome中將不在限制數(shù)據(jù),但是超過header的允許大小將會報錯
firefox限制30個
Opera第個域名限制50個
demo為了簡化操作,我所有的cookie的操作都采用js.cookie的庫,有興趣可以在github上面讀源碼。
方法名 介紹 Cookies.get(key) 獲取本地key對應的值,不存在返回undefined Cookies.set(key,value) 將key的值設置成value Cookies.set(key,{}) 支持直接保存object值 Cookies.set(key1,key2,{}) 支持同時設置多個值 Cookies.remove(\'key\') 移除key的值 Cookies.getJSON(\'key\') 獲取key的值,并且直接序列化成Object<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> </head> <body> <div id="resultDiv"> <script> $(document).ready(function(){ var visited=0; if(Cookies.get(\'visited\')!=undefined){//如果Cookie不存在返回undefined visited=Cookies.get(\'visited\')//獲取訪問次數(shù) } visited++;//添加本次訪問 Cookies.set(\'visited\',visited)//設置cookie document.getElementById(\'resultDiv\').innerHTML=visited }) </script> </div> </body> </html>
上面的demo用來記錄當前客戶端訪問網(wǎng)站的次數(shù)
localStoragelocalStorage和sessionStorage的接口是一致的,所以本章所有的案例可以直接改成sessionStorage.
方法名 作用 localStorage.setItem(\'key\',\'val\') 將key設置成val localStorage.getItem(\'key\') 獲取key的值 localStorage.removeItem(\'key\') 刪除key的值 localStorage.clear() 刪除所有的值 Demo 獲取訪問次數(shù)<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> </head> <body> <div id="resultDiv"></div> <script> $(document).ready(function(){ if(window.localStorage){//瀏覽器是否支持localStorage var numHits=localStorage.getItem(\'numHits\');//獲取numHits的值 if(!numHits) numHits=0;//如果第一次訪問就置 為0 else numHits=parseInt(numHits,10)//轉(zhuǎn)換成數(shù)值 類型 numHits++ localStorage.setItem(\'numHits\',numHits) $("#resultDiv").text(\'you have visited this site \'+numHits+\'times.\') } }) </script> </body> </html>
上面的作用是在本地存儲一個以numHits的值,表示訪問的次數(shù)
距離上次訪問的時間
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> </head> <body> <div id="resultDiv"> ? </div> <script> $(document).ready(function(){ var $resultDiv=$(\'#resultDiv\') var newUser=true; var daysSinceLastVisit; if(Cookies.get(\'lastVisit\')!=undefined){ newUser=false; var lastVisit=Cookies.get(\'lastVisit\') var now=new Date()//當前的時間 var lastVisitDate=new Date(lastVisit)//lastVisit轉(zhuǎn)換成date對象 var timeDiff=Math.abs(now.getTime()-lastVisitDate.getTime())//存在再次時間差 var daysSinceLastVisit=Math.ceil(timeDiff/(1000*3600*24))//轉(zhuǎn)換成天 } Cookies.set(\'lastVisit\',new Date(),Infinity) if(newUser){ $resultDiv.text(\'welcome to the site\') }else if(daysSinceLastVisit>20){ $resultDiv.text(\'welcome back to the site!\') }else{ $resultDiv.text(\'welcome good user!\') } }) ? </script> </body> </html>
上次的代碼主要現(xiàn)實的三個功能:
如果初次訪問輸出welcome to the site
如果上次訪問的時間超過20天輸出,welcome back to the site!
如果在20天以內(nèi),輸出:welcome good user
存儲表單數(shù)據(jù)localStorage實際上只能存儲字符串數(shù)據(jù),但是可以通過JSON.stringify和JSON.parse來存儲Object對象。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> </head> <body> <form action="#" id="myForm"> <p>Your name:<input type="text" name="name" id="name"></name:></p> <p>Your age:<input type="number" name="age" id="age"></name:></p> <p>your email:<input type="email" name="email" id="email"></p> <p><input type="submit" ></p> </form> <script> $(document).ready(function(){ if(window.localStorage){ if(localStorage.getItem(\'personForm\')){ var person=JSON.parse(localStorage.getItem(\'personForm\')) $("#name").val(person.name); $("#age").val(person.age); $("#email").val(person.email) console.log(\'restored from storage\') } $("input").on(\'input\',function(e){ var name=$("#name").val(); var age=$("#age").val(); var email=$("#email").val(); console.log(\'email\',email) var person = { "name": name, "age": age, "email": email } localStorage.setItem("personForm",JSON.stringify(person)) console.log(\'stored the from...\') }) $("#myForm").on(\'submit\',function(e){ localStorage.removeItem(\'personForm\') return true }) } }) </script> </body> </html>
上面的demo主要是:
監(jiān)聽所有表單的輸入事件,通過JSON.stringify()來將Object轉(zhuǎn)換成字符串進行存儲
進入網(wǎng)站時讀取表單數(shù)據(jù),如果存在著personForm的值就直接顯示在頁面上
點擊提交按鈕清空personForm數(shù)據(jù)
不同頁面進行通信有一次面試被問到如何實現(xiàn)幾個標簽的通信,下面的demo實際上就是做了這么一個工作。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> </head> <body> <form action="#" id="myForm"> <p>Text Value:<input type="text" id="text"></p> </form> <script> $(document).ready(function(){ if(window.localStorage){ console.log(\'test\',localStorage.getItem(\'testValue\')) if(localStorage.getItem(\'testValue\')!=undefined){ console.log(\'f1\') $(\'#text\').val(localStorage.getItem(\'testValue\')) } $(\'input\').on(\'input\',function(e){ var test=$(\'#text\').val() localStorage.setItem(\'testValue\',test) console.log(\'stored the test value.\'); }) $(window).on(\'storage\',function(e){ console.log(\'storage event fired\'); console.dir(e); }) } }) </script> </body> </html>
上面的demo我們打開兩個頁面,第一個頁面輸入內(nèi)容,第二個頁面就會觸發(fā)window的storage事件,事件的參數(shù)originalEvent對象中的newValue和oldValue表示上次的值 和當前 的值 。
兼容if (!window.localStorage) { Object.defineProperty(window, "localStorage", new (function () { var aKeys = [], oStorage = {}; Object.defineProperty(oStorage, "getItem", { value: function (sKey) { return sKey ? this[sKey] : null; }, writable: false, configurable: false, enumerable: false }); Object.defineProperty(oStorage, "key", { value: function (nKeyId) { return aKeys[nKeyId]; }, writable: false, configurable: false, enumerable: false }); Object.defineProperty(oStorage, "setItem", { value: function (sKey, sValue) { if(!sKey) { return; } document.cookie = escape(sKey) + "=" + escape(sValue) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"; }, writable: false, configurable: false, enumerable: false }); Object.defineProperty(oStorage, "length", { get: function () { return aKeys.length; }, configurable: false, enumerable: false }); Object.defineProperty(oStorage, "removeItem", { value: function (sKey) { if(!sKey) { return; } document.cookie = escape(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"; }, writable: false, configurable: false, enumerable: false }); this.get = function () { var iThisIndx; for (var sKey in oStorage) { iThisIndx = aKeys.indexOf(sKey); if (iThisIndx === -1) { oStorage.setItem(sKey, oStorage[sKey]); } else { aKeys.splice(iThisIndx, 1); } delete oStorage[sKey]; } for (aKeys; aKeys.length > 0; aKeys.splice(0, 1)) { oStorage.removeItem(aKeys[0]); } for (var aCouple, iKey, nIdx = 0, aCouples = document.cookie.split(/s*;s*/); nIdx < aCouples.length; nIdx++) { aCouple = aCouples[nIdx].split(/s*=s*/); if (aCouple.length > 1) { oStorage[iKey = unescape(aCouple[0])] = unescape(aCouple[1]); aKeys.push(iKey); } } return oStorage; }; this.configurable = false; this.enumerable = true; })()); }
當前文章:web客戶端存儲技術(shù)
本文路徑:http://chinadenli.net/article24/cjheje.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站建設、建站公司、用戶體驗、品牌網(wǎng)站制作、移動網(wǎng)站建設、微信小程序
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)