如何使用HTML5 localStorage和sessionStorage?
HTML5引入了两种类似于HTTP会话cookie的机制,用于在客户端存储结构化数据并克服以下缺点。
- Cookie包含在每个HTTP请求中,从而通过传输相同的数据来减慢Web应用程序的速度。
- Cookie的数据限制约为4KB。不足以存储所需的数据。
这两种存储机制分别是会话存储和本地存储,它们将用于处理不同的情况。
会话存储
会话存储设计用于用户正在执行单个事务的场景,但可能同时在不同的窗口中执行多个事务。
您可以尝试运行以下代码来设置会话变量并访问该变量
示例
<!DOCTYPE HTML> <html> <body> <script type="text/javascript"> if( sessionStorage.hits ){ sessionStorage.hits = Number(sessionStorage.hits) +1; } else{ sessionStorage.hits = 1; } document.write("Total Hits :" + sessionStorage.hits ); </script> <p>Refresh the page to increase number of hits.</p> <p>Close the window and open it again and check the result.</p> </body> </html>
本地存储
本地存储设计用于跨多个窗口的存储,并且持续时间超过当前会话。特别是,出于性能原因,Web应用程序可能希望将兆字节的用户数据(例如整个用户创作的文档或用户的邮箱)存储在客户端。
您可以尝试运行以下代码来设置本地存储变量,并在每次访问此页面时(甚至下次打开窗口时)访问该变量。
示例
<!DOCTYPE HTML> <html> <body> <script type="text/javascript"> if( localStorage.hits ){ localStorage.hits = Number(localStorage.hits) +1; } else{ localStorage.hits = 1; } document.write("Total Hits :" + localStorage.hits ); </script> <p>Refresh the page to increase number of hits.</p> <p>Close the window and open it again and check the result.</p> </body> </html>
广告