网页中的存储可以存放在客户端,也可以存放在服务器端。虽然存放在服务器非常的安全,但是如果每次都从服务器去读取数据,进行I/O操作,那么我想服务器的压力恐怕不是一点点的大。所以有人就考虑把部分信息存放在客户端,减轻服务器的压力。
其中web存储又分为本地存储和回话存储。他们的主要区别是本地存储就是存放在浏览器中,只要你不去清除,那么一直存在,适合存放一些长期保持的数据。而对于会话存储只要你把浏览器关闭,那么这些数据就不存在了(被浏览器清除)。根据他们的特点,我们可以知道本地存储主要是存放访客在将来还可以看到的数据,而对于会话存储则存放一些从一个页面传递给下一个页面的一些内容。
对于我们的代码编写而言,他们的操作一模一样,所以下面就只对本地存储做介绍。接下来通过代码说明:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input id="name" type="text">
<button id="save">保存</button>
<button id="get">取值</button>
<button id="delete">删除</button>
<script type="text/javascript">
window.οnlοad=function(){
var oName = document.getElementById("name");
var oSave = document.getElementById("save");
var oGet = document.getElementById("get");
var oDelete = document.getElementById("delete");
oSave.οnclick=function(){
// 存放主要是通过键值对的方式,如果是会话存放,则是sessionStorage
// 通过localStorage.setItem存放,通过localStorage.getItem获取
localStorage.setItem("username",oName.value);
oName.value = "";
}
oGet.οnclick=function(){
if(localStorage.getItem("username")==null){
alert("你没有保存这个值");
}else{
var name = localStorage.getItem("username");
alert(name+"");
}
}
oDelete.οnclick=function(){
// 如果想要删除全部的话,那么就使用localStorage.clear();
localStorage.removeItem("username");
}
}
</script>
</body>
</html>
介绍了上面最基本的读取,下面总结一下读取所有的存储内容,如果读取。因为我们有时候忘记了key值,那么就只有遍历出来看看,当然也可以通过其他方式查看
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<ul id="datalist">
</ul>
<script type="text/javascript">
window.οnlοad=function(){
localStorage.setItem("username","xiaoD");
localStorage.setItem("password","123");
localStorage.setItem("gender","男");
localStorage.setItem("age","21");
var oItem = document.getElementById("datalist");
for(var i=localStorage.length-1;i>=0;i--){
var key = localStorage.key(i);
var item = localStorage.getItem(key);
var newItem = document.createElement("li");
newItem.innerHTML = key + "--" + item;
oItem.appendChild(newItem);
}
}
</script>
</body>
</html>
一切都很好,用的很舒服,记得曾经有位老师曾经说过,凡是我们觉得好用的东西,总是会有那么一点bug。这个也不例外,具体什么问题呢,也就是我们再读取一个数字或者时间的时候,读取出来的是字符串,见下面代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input id="num" type="text">
<input id="time" type="text">
<script type="text/javascript">
window.οnlοad=function(){
localStorage.setItem("age",21);
var oNum = document.getElementById("num");
oNum.value = localStorage.getItem("age")+5; //最后的结果为215
//解决办法
oNum.value = Number(localStorage.getItem("age"))+5;//最后的结果为26
var today = new Date();
var todayString = today.getFullYear()+"-"+Number(today.getMonth()+1)+"-"+today.getDate();
localStorage.setItem("time",todayString);
var oTime = document.getElementById("time");
oTime.value = new Date(localStorage.getItem("time")).getFullYear();//转换
}
</script>
</body>
</html>
在测试的时候需要注意,在本地测试的时候可能会出错,这时候可以放在服务器上测试。