HTML5 Web 存儲
HTML5 Web 存儲
HTML5 web 存儲,一個比cookie更好的本地存儲方式。
什么是 HTML5 Web 存儲?
使用HTML5可以在本地存儲用戶的瀏覽數據。
早些時候,本地存儲使用的是cookies。但是Web 存儲需要更加的安全與快速. 這些數據不會被保存在服務器上,但是這些數據只用于用戶請求網站數據上.它也可以存儲大量的數據,而不影響網站的性能.
數據以 鍵/值 對存在, web網頁的數據只允許該網頁訪問使用。
localStorage 和 sessionStorage?
There are two new objects for storing data on the client:
localStorage - 沒有時間限制的數據存儲
sessionStorage - 針對一個 session 的數據存儲
在使用 web 存儲前,應檢查瀏覽器是否支持 localStorage 和sessionStorage:
if(typeof(Storage)!=="undefined") { // Yes! localStorage and sessionStorage support! // Some code..... } else { // Sorry! No web storage support.. }
localStorage 對象
localStorage 對象存儲的數據沒有時間限制。第二天、第二周或下一年之后,數據依然可用。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <div id="result"></div> <script> if(typeof(Storage)!=="undefined") { localStorage.lastname="Smith"; document.getElementById("result").innerHTML="Last name: " + localStorage.lastname; } else { document.getElementById("result").innerHTML="Sorry, your browser does not support web storage..."; } </script> </body> </html>
實例解析:
使用 key="lastname" 和value="Smith" 創(chuàng)建一個 localStorage 鍵/值對
檢索鍵值為"lastname" 的值然后將數據插入 id="result"的元素中
提示:?鍵/值對通常以字符串存儲,你可以按自己的需要轉換該格式。
下面的實例展示了用戶點擊按鈕的次數. 代碼中的字符串值轉換為數字類型:
<!DOCTYPE html> <html> <head> <script> function clickCounter() { if(typeof(Storage)!=="undefined") { 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)."; } else { document.getElementById("result").innerHTML="Sorry, your browser does not support web storage..."; } } </script> </head> <body> <p><button onclick="clickCounter()" type="button">點我</button></p> <div id="result"></div> <p>單擊該按鈕查看計數器增加.</p> <p>關閉瀏覽器選項卡(或窗口),再試一次,計數器將繼續(xù)計數(不是重置)。</p> </body> </html>
sessionStorage 對象
sessionStorage 方法針對一個 session 進行數據存儲。當用戶關閉瀏覽器窗口后,數據會被刪除。
如何創(chuàng)建并訪問一個 sessionStorage::
<!DOCTYPE html> <html> <head> <script> function clickCounter() { if(typeof(Storage)!=="undefined") { 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."; } else { document.getElementById("result").innerHTML="Sorry, your browser does not support web storage..."; } } </script> </head> <body> <p><button onclick="clickCounter()" type="button">Click me!</button></p> <div id="result"></div> <p>單擊該按鈕查看計數器增加.</p> <p>關閉瀏覽器選項卡(或窗口),再試一次,計數器將繼續(xù)計數(不是重置)。</p> </body> </html>