html5本地存储-WebStorage

来源:互联网 发布:a byte of python pdf 编辑:程序博客网 时间:2024/04/30 12:34
Html5本地存储有两种方式
第一种为WebStorage
第二种为Web SQL Database
本节当中主要介绍WebStorage
WebStorage提供了两种存储类型的API接口:sessionStorage和localStorage。两者的用法相同,只不过存在的生命周期不同。
sessionStorage只保存在存储他的当前窗口或由当前窗口新建窗口,直到相关联的标签页关闭。
localStorage保存在客户端,数据时永久存储的,除非用户或者程序对其执行删除的操作
接下来我们举一个例子,使用localStorage存储json数据
<!DOCTYPEhtml>
<html>
<head>
   <metacharset="utf-8">
  <title>使用localStorage本地存储JSON数据</title>
  <script>
      window.onload=function()
      {
         //首先判断浏览器是否支持localStorage
         if(window.localStorage)
          {
             //定义JSON格式的字符串
             var userData={
                name:"baohanqing",
                age:23,
                address:"北京朝阳",
                interest:"篮球"
             };

             //存储userData数据
            //JSON.stringify()表示的市将字符串数据格式转换成JSON对象
            localStorage.setItem("userData",JSON.stringify(userData));

             //读取我们的JSON数据
             //JSON.parse()表示的是将JSON对象转换为原来的格式
             varmyInfo=JSON.parse(localStorage.getItem("userData"));
             alert(myInfo.name);
          }
          else
          {
             alert("您的浏览器不支持LocalStorage");
          }
      }


  </script>
</head>
<body>
</body>
</html>
0 0