摘要:cookie的优势能够与服务器共享状态,每次通过ajax请求的时候都会将cookie附带到请求的header,服务端能够直接读取到本地存储的数据。
cookie的优势能够与服务器共享状态,每次通过ajax请求的时候都会将cookie附带到请求的header,服务端能够直接读取到本地存储的数据。
GET /sample_page.html HTTP/1.1 Host: www.example.org Cookie: yummy_cookie=choco; tasty_cookie=strawberry
浏览器限制情况
cookie在chrome中将不在限制数据,但是超过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\')//获取访问次数 } visited++;//添加本次访问 Cookies.set(\'visited\',visited)//设置cookie document.getElementById(\'resultDiv\').innerHTML=visited }) </script> </div> </body> </html>
上面的demo用来记录当前客户端访问网站的次数
localStoragelocalStorage和sessionStorage的接口是一致的,所以本章所有的案例可以直接改成sessionStorage.
方法名 作用 localStorage.setItem(\'key\',\'val\') 将key设置成val localStorage.getItem(\'key\') 获取key的值 localStorage.removeItem(\'key\') 删除key的值 localStorage.clear() 删除所有的值 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> <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)//转换成数值 类型 numHits++ localStorage.setItem(\'numHits\',numHits) $("#resultDiv").text(\'you have visited this site \'+numHits+\'times.\') } }) </script> </body> </html>
上面的作用是在本地存储一个以numHits的值,表示访问的次数
距离上次访问的时间
<!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转换成date对象 var timeDiff=Math.abs(now.getTime()-lastVisitDate.getTime())//存在再次时间差 var daysSinceLastVisit=Math.ceil(timeDiff/(1000*3600*24))//转换成天 } 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>
上次的代码主要现实的三个功能:
如果初次访问输出welcome to the site
如果上次访问的时间超过20天输出,welcome back to the site!
如果在20天以内,输出:welcome good user
存储表单数据localStorage实际上只能存储字符串数据,但是可以通过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主要是:
监听所有表单的输入事件,通过JSON.stringify()来将Object转换成字符串进行存储
进入网站时读取表单数据,如果存在着personForm的值就直接显示在页面上
点击提交按钮清空personForm数据
不同页面进行通信有一次面试被问到如何实现几个标签的通信,下面的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我们打开两个页面,第一个页面输入内容,第二个页面就会触发window的storage事件,事件的参数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; })()); }
相关文章推荐
樱桃cherry.com域名价格或达7位数美元2022-09-06
紫燕食品上市,卤味市场域名哪家强?2022-09-27
新一期域名交易排行榜,国别域名MA.ca成无冕之王2022-09-27
威瑞信发布2022年Q2行业简报:.com注册量下降2022-09-27
域名Keys.xyz被元宇宙游戏终端收购2022-09-20