HTML5 web 存儲,一個比cookie更好的本地存儲方式。
什么是 HTML5 Web 存儲?
使用HTML5可以在本地存儲用戶的瀏覽數(shù)據(jù)。
早些時候,本地存儲使用的是cookies。但是Web 存儲需要更加的安全與快速. 這些數(shù)據(jù)不會被保存在服務(wù)器上,但是這些數(shù)據(jù)只用于用戶請求網(wǎng)站數(shù)據(jù)上.它也可以存儲大量的數(shù)據(jù),而不影響網(wǎng)站的性能.
數(shù)據(jù)以 鍵/值 對存在, web網(wǎng)頁的數(shù)據(jù)只允許該網(wǎng)頁訪問使用。
瀏覽器支持
Internet Explorer 8+, Firefox, Opera, Chrome, 和 Safari支持Web 存儲。
注意: Internet Explorer 7 及更早IE版本不支持web 存儲.
localStorage 和 sessionStorage
There are two new objects for storing data on the client:
localStorage – 沒有時間限制的數(shù)據(jù)存儲
sessionStorage – 針對一個 session 的數(shù)據(jù)存儲
在使用 web 存儲前,應(yīng)檢查瀏覽器是否支持 localStorage 和sessionStorage:
if(typeof(Storage)!=="undefined") { // Yes! localStorage and sessionStorage support! // Some code..... } else { // Sorry! No web storage support.. }
localStorage 對象
localStorage 對象存儲的數(shù)據(jù)沒有時間限制。第二天、第二周或下一年之后,數(shù)據(jù)依然可用。
實例
localStorage.lastname="Smith";document.getElementById("result").innerHTML="Last name: "+ localStorage.lastname;
實例解析:
使用 key="lastname" 和value="Smith" 創(chuàng)建一個 localStorage 鍵/值對
檢索鍵值為"lastname" 的值然后將數(shù)據(jù)插入 id="result"的元素中
提示: 鍵/值對通常以字符串存儲,你可以按自己的需要轉(zhuǎn)換該格式。
下面的實例展示了用戶點擊按鈕的次數(shù). 代碼中的字符串值轉(zhuǎn)換為數(shù)字類型:
if (localStorage.clickcount) { localStorage.clickcount=Number(localStorage.clickcount)+1; } else { localStorage.clickcount=1; } document.getElementById("result").innerHTML="You have clicked the button " + localStorage.clickcount + " time(s).";
sessionStorage 對象
sessionStorage 方法針對一個 session 進行數(shù)據(jù)存儲。當(dāng)用戶關(guān)閉瀏覽器窗口后,數(shù)據(jù)會被刪除。
如何創(chuàng)建并訪問一個 sessionStorage::
if (sessionStorage.clickcount) { sessionStorage.clickcount=Number(sessionStorage.clickcount)+1; } else { sessionStorage.clickcount=1; } document.getElementById("result").innerHTML="You have clicked the button " + sessionStorage.clickcount + " time(s) in this session.";
【相關(guān)推薦】
1. 特別推薦:“php程序員工具箱”V0.1版本下載