HTML5之WEB Storage
阿新 • • 發佈:2018-11-21
什麼是HTML5 web storage?
使用HTML5,web頁面能夠使用使用者的瀏覽器本地儲存資料。
在曾經,通常我們使用cookie來儲存使用者資料。然而使用web儲存更加安全和高速。資料不再包括在每個server請求中。僅僅存在你須要的時候。
同一時候我們也能夠儲存大量資料。而不影響站點的效能。
資料都儲存成key/value形式,一個web頁面僅僅能夠訪問自己的資料。
瀏覽器支援
IE8+。Firefox,Chrome,Opera和Safari 5都支援這個特性。
注意IE7和更早版本號不支援這個特性。
localStorage和sessionStorage
這裡有倆個新的用來儲存資料的屬性:
- localStorage - 沒有過期時間的方式儲存資料
- sessionStorage - 儲存資料到session
在使用web storage之前,檢查瀏覽器是否支援localStorage和sessionStorage:
- if(typeof(Storage)!=="undefined"){
- // Yes! localStorage and sessionStorage support!
- // Some code.....
- }else{
-
- }
localStorage Object
localStorage物件儲存資料沒有過期時間的問題。
資料在瀏覽器關閉後不會刪除,並且一直有效。
- localStorage.lastname="Smith";
- document.getElementById("result").innerHTML="Last name: "
- + localStorage.lastname;
線上演示
程式碼說明:
- 建立了一個localStorage 鍵值對,使用key="lastname"。 value="Smith" 。
- 得到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物件和localStorage物件相似,除了儲存的資料僅僅在當前session中有效。資料將會在使用者關閉瀏覽器窗體時失效。
以下程式碼在當前的session中計算了使用者點選的次數:
- 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.";