一 介绍
HTML5 web存储,一个比cookie更好的本地存储方式。
1、什么是HTML5 Web存储
使用HTML5可以在本地存储用户的浏览数据。
早些时候,本地存储使用的是cookie。
但是Web存储需要更加的安全与快速,这些数据不会被保存在服务器上,但是这些数据只用于用户请求网站数据上,它也可以存储大量的数据,而不影响网站的性能。
数据以 键/值 对存在, web网页的数据只允许该网页访问使用。
2、localStorage和sessionStorage
客户端存储数据的两个对象为:
localStorage - 没有时间限制的数据存储,第二天、第二周或下一年之后,数据依然可用。
sessionStorage - 针对一个 session 的数据存储,当用户关闭浏览器窗口后,数据会被删除。
二 代码
<!DOCTYPE html> <html> <head> <meta name="author" content="Yeeku.H.Lee(CrazyIt.org)" /> <meta http-equiv="Content-Type" content="text/html; charset=GBK" /> <title> Storage示例 </title> </head> <body> <h2> Storage示例</h2> <input type="text" id="input"/> <!-- 定义是否用Local Storage保存的数据的复选框 --> 使用Local Storage保存:<input type="checkbox" id="local"/> <div id="show"></div> <input type="button" value="保存数据" οnclick="saveStorage('input');"/> <input type="button" value="读取数据" οnclick="loadStorage('show');"/> <script type="text/javascript"> var saveStorage = function(id) { // 如果勾选了复选框,使用Local Storage保存数据 // 否则使用Session Storage保存数据 var checked = document.getElementById("local").checked; var storage = checked ? localStorage : sessionStorage; var target = document.getElementById(id); storage.setItem("message" , target.value); } var loadStorage = function(id) { // 如果勾选了复选框,使用Local Storage保存数据 // 否则使用Session Storage保存数据 var checked = document.getElementById("local").checked; var storage = checked ? localStorage : sessionStorage; var target = document.getElementById(id); // 读取数据 target.innerHTML = storage.getItem("message"); } </script> </body> </html>
三 运行结果