在實際使用過程中,經常會遇到需要在頁面間進行傳值的情況,最初設想一定需要后端才能進行數據的存儲和讀取,或者在本地使用一個cookie進行保存,直到了解到HTML5 Web存儲
使用HTML5的新特性可以在本地存儲用戶的瀏覽數據。相比之前的cookie,Web 存儲更加的安全與快速. 這些數據不會被保存在服務器上,數據只用於用戶請求網站數據上.它也可以存儲大量的數據,而不影響網站的性能.
數據以“鍵/值”對存在, web網頁的數據只允許該網頁訪問使用
方法: localStorage 和 sessionStorage (客戶端存儲)
- localStorage - 用於長久保存整個網站的數據,保存的數據沒有過期時間,直到手動去除。
- sessionStorage - 用於臨時保存同一窗口(或標簽頁)的數據,在關閉窗口或標簽頁之后將會刪除這些數據。
在使用 web 存儲前,檢查瀏覽器是否支持 localStorage 和sessionStorage:
if(typeof(Storage)!=="undefined") { // 支持 localStorage sessionStorage 對象 // 事件函數 } else { // 不支持 web 存儲。 }
(只要不是老掉牙的IE,基本沒問題的,現在的瀏覽器都支持H5的)
寫的一個小demo,用於理解:在第一個頁面中輸入,跳轉后第二個頁面上讀取數據
<form> <fieldset id="submit"> <input type="text" id="one" name="one"></select> <input type="text" id="two" name="two"> <input type="button" value="submit" onclick="submit()"> </fieldset> </form>
function submit(){ if(document.getElementById("submit").value!=""){ var Key=document.getElementById("submit"); localStorage.name = Key.value; location.href = 'index.html'; }else{ alert("error"); } }
//index.html中 <script> //讀取保存結果 var searchKey = localStorage["name"]; </script>
另菜鳥教程上有一個demo,個人感覺很不錯:
<div> <label for="sitename">網站名(key):</label> <input type="text" id="sitename" name="sitename" class="text"/> <label for="siteurl">網址(value):</label> <input type="text" id="siteurl" name="siteurl"/> <input type="button" onclick="save()" value="新增記錄"/> <label for="search_site">輸入網站名:</label> <input type="text" id="search_site" name="search_site"/> <input type="button" onclick="find()" value="查找網站"/> <p id="find_result"><br/></p> </div>
//保存數據 function save(){ var siteurl = document.getElementById("siteurl").value; var sitename = document.getElementById("sitename").value; localStorage.setItem(sitename, siteurl); alert("添加成功"); } //查找數據 function find(){ var search_site = document.getElementById("search_site").value; var sitename = localStorage.getItem(search_site); var find_result = document.getElementById("find_result"); find_result.innerHTML = search_site + "的網址是:" + sitename; }
參考鏈接:
菜鳥教程:http://www.runoob.com/html/html5-webstorage.html
w3school: http://www.w3school.com.cn/html5/html_5_webstorage.asp