HTML5 Web Storage制作简易数据库

Web Storage分为两种:

sessionStorage:将数据保存在session对象中。所谓session,是指用户在浏览某个网站时,从进入网站到浏览器关闭所经过的这段时间,也就是用户浏览这个网站所花费的时间。session对象可以用来保存在这段时间内所要求保存的任何数据。

localStorage:将数据保存在客户端本地硬件设备中,即使浏览器被关闭了,该数据仍然存在,下次打开浏览器访问网站时仍然可以继续使用。

这两者的区别在于,sessionStorage为临时保存,而localStorage为永久保存


sessionStorage
保存数据的方法:
sessionStorage.setItem(“key”,”value”);
或者
sessionStorage.key=”value”;
读取数据的方法:
sessionStorage.getItem(“key”,”value”);
或者
sessionStorage.key;

localStorage
保存数据的方法:
localStorage.setItem(“key”,”value”);
或者
localStorage.key=”value”;
读取数据的方法:
localStorage.getItem(“key”,”value”);
或者
localStorage.key;

清除localStorage保存的永久数据方法为:localStorage.clear()


简单的存储和检索用户名得到信息的功能页面

HTML5 Web Storage制作简易数据库_第1张图片


<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>web storage简易数据库title>
head>
<body>
 <table>
     <tr>
         <td>姓名:td>
         <td><input type="text" id="name"/>td>
     tr>
     <tr>
         <td>email:td>
         <td><input type="email" id="email"/>td>
     tr>
     <tr>
         <td>电话号码:td>
         <td><input type="tel" id="tel"/>td>
     tr>
     <tr>
         <td>备注:td>
         <td><input type="text" id="memo"/>td>
     tr>
     <tr>
         <td>td>
         <td><input type="button" value="保存" onclick="saveStorage();"/>td>
     tr>
 table>
 <hr/>
 <p>检索:<input type="text" id="find"/>
         <input type="button" value="检索" onclick="findStorage();"/>
 p>
<p id="msg">p>
 <script>
     function saveStorage(){
         var data=new Object();//新建一个对象
         data.name=document.getElementById("name").value;//字面量定义对象属性
         data.email=document.getElementById("email").value;
         data.tel=document.getElementById("tel").value;
         data.memo=document.getElementById("memo").value;
         var str=JSON.stringify(data);//把data作为JSON类数据赋值
         localStorage.setItem(data.name,str);//用localStorage永久存储,自定义关键字为data.name的值
         alert("保存成功");
     }

     function findStorage(){
         var ofind=document.getElementById("find").value;//获取检索text中的值
         var odate= JSON.parse(localStorage.getItem(ofind));//根据检索的值读取数据库内的对应信息并转化为对象赋值
         var omsg=document.getElementById("msg")
         var result="姓名:"+odate.name+"
"
;//添加对象属性到omsg中 result+="email:"+odate.email+"
"
; result+="电话号码:"+odate.tel+"
"
; result+="备注:"+odate.memo+"
"
; omsg.innerHTML=result; }
script> body> html>

你可能感兴趣的:(html5)