本地存儲

存儲
cookie   用於保存服務器發送回來的用戶信息、瀏覽信息等。一個cookie文件只有4kb,即能裝下4000個英文字或者2000箇中文字。能與服務器交互。

HTML5提供了兩種本地存儲方式:localStorage和sessionStorage,此爲兩個對象,能夠看作JSON對象,存儲大小無限制,但通常是在本地存儲,存在瀏覽器中。

localStorage和sessionStorage
二者區別在於存儲時間的區別,localStorage永久存儲,直到卸載瀏覽器或手動清空;sessionStorage存儲時間爲會話時間,即瀏覽器打開直到瀏覽器關閉。

localStorage用法
localStorage的機制將對象轉換爲字符串進行了存儲,則須要用到JSON方法,存儲時用JSON.stringify(),對象轉字符串;取值時JSON.parse()字符串轉對象。

          var user={username:"def",psw:"1111"};    //存儲
         localStorage.user=JSON.stringify(user);

            var user=JSON.parse(localStorage.user);   //獲取
            console.log(user);       //Object {username: "def", psw: "1111"}
            console.log(user.username);    //def
            console.log(typeof (user));    //object
若不使用JSON方法,則會出現如下狀況:

           localStorage.user={username:"abc",pwd:"123"};   //存儲
          
             var user=localStorage.user;      //獲取
             console.log(user);    //[object Object]
             console.log(user.username);       //undefined
             console.log(typeof (user));      //string瀏覽器

相關文章
相關標籤/搜索