使用本地存储Storage实现留言

来源:互联网 发布:holo是什么软件 编辑:程序博客网 时间:2024/06/06 01:34

1.在传统的HTML时代,开发者如果需要在客户端存储少量数据,只能通过cookie来实现,但Cookie存在如下三点不足:大小被限制为3KB;会包含在每个HTTP请求中向服务器发送,会导致多次发送重复数据;在网络传输时并未加密,存在一些安全隐患

2.HTML5新增了Web Storage功能,可以让应用程序在客户端运行时在客户端保存数据。H5提供了两个Web Storage:Session Storage:基于Session的Web Storage。保存的数据的生存期限和Session相同,当Session结束时,Session Storage保存的数据也就丢失了;Local Storage:保存在用户磁盘的Web Storage,保存的数据生存期限很长,只有当用户或者程序显式的清楚这些数据才会消失

3.Storage(包括local Storage和session Storage)提供了如下属性方法:

1.length:返回该Storage里保存了多少组键值对2.key(index):返回该Storage中的第index个Key3.getItem(key):返回该Storage指定的key对应的value值4.set(key,value):向Storage存入指定的键值对5.removeItem(key):向Storage移除指定的key的键值对6.clear():清除该Storage中的所有键值对

4.实现代码:

<!Doctype html><html>    <head>        <title>本地存储数据</title>    </head>    <body>        <form>            <label for="msg">输入内容:</label>            <textarea rows="4" colw="20" id="            <br />            <input type="button" value="留言" id="btn" />            <br />            <input type="reset" value="重置" />            <br/>        </form>        <input type="button" id="sbtn" value="读取" />        <input type="button" id="cbtn" value="清除" />        <div id="show"></div>        <script>            window.onload = function(){                /* 使用local Storage */                var message = document.getElementById("msg").innerHTML ;                localStorage.setItem("message",message) ;                /*使用local Storage读取本地数据*/                document.getElementById("sbtn").onclick = function() {                    document.getElementById("show").innerHTML = localStorage.get("message") ;            };                /*使用local Storage清除数据*/                document.getElementById("cbtn").onclick = function() {                    document.getElementById("show").innerHTML = "" ;                    localStroage.clear() ;                    alert("清除成功") ;                };            };
0 0
原创粉丝点击