如何使用 HTML5 localStorage 和 sessionStorage?


HTML5 类似于 HTTP 会话 Cookie,引入了两种用于存储客户端结构化数据的机制,以克服以下缺点。

  • Cookie 随每次 HTTP 请求一同发送,从而通过传输相同数据减慢了 Web 应用程序的速度。
  • Cookie 限制为大约 4 KB 的数据。这不足以存储所需数据。

这两种存储机制是会话存储和本地存储,它们可用于处理不同的情况。

会话存储

会话存储设计用于用户执行单一事务但可以在同一时间在不同的浏览器窗口中执行多个事务的情况。

你可以尝试运行以下命令来设置会话变量并访问该变量

示例

在线演示

<!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>

更新日期: 2020 年 5 月 18 日

437 次浏览

开启您的 职业生涯

完成课程,获得认证

入门
广告
© . All rights reserved.