web客戶端存儲(chǔ)技術(shù)

cookie

cookie的優(yōu)勢(shì)能夠與服務(wù)器共享狀態(tài),每次通過(guò)ajax請(qǐng)求的時(shí)候都會(huì)將cookie附帶到請(qǐng)求的header,服務(wù)端能夠直接讀取到本地存儲(chǔ)的數(shù)據(jù)。

成都創(chuàng)新互聯(lián)公司專注于桐廬網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗(yàn)。 熱誠(chéng)為您提供桐廬營(yíng)銷型網(wǎng)站建設(shè),桐廬網(wǎng)站制作、桐廬網(wǎng)頁(yè)設(shè)計(jì)、桐廬網(wǎng)站官網(wǎng)定制、微信小程序服務(wù),打造桐廬網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供桐廬網(wǎng)站排名全網(wǎng)營(yíng)銷落地服務(wù)。

GET /sample_page.html HTTP/1.1 Host: www.example.org Cookie: yummy_cookie=choco; tasty_cookie=strawberry

瀏覽器限制情況

cookie在chrome中將不在限制數(shù)據(jù),但是超過(guò)header的允許大小將會(huì)報(bào)錯(cuò)

firefox限制30個(gè)

Opera第個(gè)域名限制50個(gè)

demo

為了簡(jiǎn)化操作,我所有的cookie的操作都采用js.cookie的庫(kù),有興趣可以在github上面讀源碼。

方法名 介紹  Cookies.get(key) 獲取本地key對(duì)應(yīng)的值,不存在返回undefined Cookies.set(key,value) 將key的值設(shè)置成value Cookies.set(key,{}) 支持直接保存object值 Cookies.set(key1,key2,{}) 支持同時(shí)設(shè)置多個(gè)值 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\')//獲取訪問(wèn)次數(shù) } visited++;//添加本次訪問(wèn) Cookies.set(\'visited\',visited)//設(shè)置cookie document.getElementById(\'resultDiv\').innerHTML=visited }) </script> </div> </body> </html>

上面的demo用來(lái)記錄當(dāng)前客戶端訪問(wèn)網(wǎng)站的次數(shù)

localStorage

localStorage和sessionStorage的接口是一致的,所以本章所有的案例可以直接改成sessionStorage.

方法名 作用 localStorage.setItem(\'key\',\'val\') 將key設(shè)置成val localStorage.getItem(\'key\') 獲取key的值 localStorage.removeItem(\'key\') 刪除key的值 localStorage.clear() 刪除所有的值 Demo 獲取訪問(wèn)次數(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;//如果第一次訪問(wèn)就置 為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>

上面的作用是在本地存儲(chǔ)一個(gè)以numHits的值,表示訪問(wèn)的次數(shù)

距離上次訪問(wèn)的時(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()//當(dāng)前的時(shí)間 var lastVisitDate=new Date(lastVisit)//lastVisit轉(zhuǎn)換成date對(duì)象 var timeDiff=Math.abs(now.getTime()-lastVisitDate.getTime())//存在再次時(shí)間差 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)實(shí)的三個(gè)功能:

如果初次訪問(wèn)輸出welcome to the site

如果上次訪問(wèn)的時(shí)間超過(guò)20天輸出,welcome back to the site!

如果在20天以內(nèi),輸出:welcome good user

存儲(chǔ)表單數(shù)據(jù)

localStorage實(shí)際上只能存儲(chǔ)字符串?dāng)?shù)據(jù),但是可以通過(guò)JSON.stringify和JSON.parse來(lái)存儲(chǔ)Object對(duì)象。

<!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)聽(tīng)所有表單的輸入事件,通過(guò)JSON.stringify()來(lái)將Object轉(zhuǎn)換成字符串進(jìn)行存儲(chǔ)

進(jìn)入網(wǎng)站時(shí)讀取表單數(shù)據(jù),如果存在著personForm的值就直接顯示在頁(yè)面上

點(diǎn)擊提交按鈕清空personForm數(shù)據(jù)

不同頁(yè)面進(jìn)行通信

有一次面試被問(wèn)到如何實(shí)現(xiàn)幾個(gè)標(biāo)簽的通信,下面的demo實(shí)際上就是做了這么一個(gè)工作。

<!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我們打開(kāi)兩個(gè)頁(yè)面,第一個(gè)頁(yè)面輸入內(nèi)容,第二個(gè)頁(yè)面就會(huì)觸發(fā)window的storage事件,事件的參數(shù)originalEvent對(duì)象中的newValue和oldValue表示上次的值 和當(dāng)前 的值 。

兼容

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; })()); }

當(dāng)前文章:web客戶端存儲(chǔ)技術(shù)
本文路徑:http://muchs.cn/article24/cjheje.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站建設(shè)、建站公司用戶體驗(yàn)、品牌網(wǎng)站制作、移動(dòng)網(wǎng)站建設(shè)微信小程序

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)