HTML5 web 儲存,一個比cookie更好的本機儲存方式。
什麼是 HTML5 Web 儲存?
使用HTML5可以在本機上儲存使用者的瀏覽資料。
早期,本地儲存使用的是cookies。但是Web 儲存需要更加的安全與快速. 這些數據不會被保存在伺服器上,但是這些數據只用於用戶請求網站數據上.它也可以儲存大量的數據,而不影響網站的性能.
資料以鍵/值對存在, web網頁的資料只允許該網頁存取使用。
瀏覽器支援
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 - 沒有時間限制的資料儲存
sessionStorage - 針對一個session 的資料儲存
在使用web 儲存前,應檢查瀏覽器是否支援localStorage 和sessionStorage:
if(typeof(Storage)!=="undefined") { // Yes! localStorage and sessionStorage support! // Some code..... } else { // Sorry! No web storage support.. }
localStorage 物件
localStorage 物件儲存的資料沒有時間限制。第二天、第二週或下一年之後,數據仍然可用。
實例
localStorage.lastname="Smith";document.getElementById("result").innerHTML="Last name: "+ localStorage.lastname;
實例解析:
使用key="lastname" 和value="Smith" 建立一個localStorage 鍵/值對
檢索鍵值為"lastname" 的值然後將資料插入id="result"的元素中
提示: 鍵/值對通常以字串存儲,你可以按自己的需求轉換該格式。
下面的實例展示了使用者點擊按鈕的次數。程式碼中的字串值轉換為數字類型:
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 進行數據儲存。當使用者關閉瀏覽器視窗後,資料會被刪除。
如何建立並存取一個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.";
【相關推薦】
以上是HTML5Web 儲存實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!