---
title: "HTML5的Web存储应用"
author: "cakin24"
date: "2017-04-22T19:33:14Z"
tags: ["HTML5", "Web"]
categories: ["编程语言"]
slug: "html5-web"
draft: false
lastmod: "2017-04-22T19:33:14Z"
id: 2370806
url: "https://cakin24.iteye.com/blog/2370806"
---

**一 介绍**

HTML5 web存储,一个比cookie更好的本地存储方式。

1、什么是HTML5 Web存储

使用HTML5可以在本地存储用户的浏览数据。

早些时候,本地存储使用的是cookie。

但是Web存储需要更加的安全与快速，这些数据不会被保存在服务器上，但是这些数据只用于用户请求网站数据上，它也可以存储大量的数据，而不影响网站的性能。

数据以 键/值 对存在, web网页的数据只允许该网页访问使用。

2、localStorage和sessionStorage 

客户端存储数据的两个对象为：

localStorage - 没有时间限制的数据存储，第二天、第二周或下一年之后，数据依然可用。

sessionStorage - 针对一个 session 的数据存储，当用户关闭浏览器窗口后，数据会被删除。

**二 代码**

```
<!DOCTYPE html>
<html>
<head>
	<meta name="author" content="Yeeku.H.Lee(CrazyIt.org)" />
	<meta http-equiv="Content-Type" content="text/html; charset=GBK" /> 
	<title> Storage示例 </title>  
</head>  
<body>
	<h2> Storage示例</h2>  
	<input type="text" id="input"/>
	<!-- 定义是否用Local Storage保存的数据的复选框 -->
	使用Local Storage保存：<input type="checkbox" id="local"/>
	<div id="show"></div>
	<input type="button" value="保存数据"
		onclick="saveStorage('input');"/> 
	<input type="button" value="读取数据"
		onclick="loadStorage('show');"/>
	<script type="text/javascript">
		var saveStorage = function(id)
		{
			// 如果勾选了复选框，使用Local Storage保存数据
			// 否则使用Session Storage保存数据
			var checked = document.getElementById("local").checked;
			var storage = checked ? localStorage : sessionStorage;
			var target = document.getElementById(id);
			storage.setItem("message" , target.value);
		}
		var loadStorage = function(id)
		{
			// 如果勾选了复选框，使用Local Storage保存数据
			// 否则使用Session Storage保存数据
			var checked = document.getElementById("local").checked;
			var storage = checked ? localStorage : sessionStorage;
			var target = document.getElementById(id);
			// 读取数据
			target.innerHTML = storage.getItem("message");
		}
	</script>
</body>
</html>
```

 

 

**三 运行结果**

![](http://dl2.iteye.com/upload/attachment/0124/5077/fa8619a1-7ea6-3edc-b7a2-cd4464bfc278.png)