常见的本地存储方式之localStroage、sessionSt
2017-12-29 本文已影响0人
浪子闲人
HTML5 提供了两种在客户端存储数据的新方(HTML 5 Web 存储):
- localStorage - 没有时间限制的数据存储
- sessionStorage - 针对一个 session 的数据存储
localstroage
localstorage按照对象的形式存储数据,因此其key只能为字符串,共包含5个常用的API.
- setItem
- getItem
- removeItem
- length
- clear
如下的代码执行
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta name="author" content="UXDC"/>
<meta name='viewport' content='initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'>
<meta name="apple-mobile-web-app-capable" content="yes"/>
<meta name="format-detection" content="telphone=no, email=no"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="Cache-Control" content="no-siteapp" />
<meta http-equiv="x-rim-auto-match" content="none">
<meta name="HandheldFriendly" content="true">
<meta name="format-detection" content="telephone=no" />
<title>滴滴企业版</title>
<script type="text/javascript">
// html localstroage
var localstroage = window.localStorage;
// set item
localstroage.setItem('username', 'lijincai');
localstroage.setItem('openid','ksjhfkjajkdfjkszdjfksad');
localstroage.setItem('uid','10001');
console.log(localstroage);
// get item
localstroage.getItem('username');
// remove item
localstroage.removeItem('openid');
console.log(localstroage)
// length
console.log(localstroage.length);
// clear
localstroage.clear();
console.log(localstroage)
</script>
</head>
<body>
<div id="jqueryId">test</div>
</body>
</html>
我们可以得到如下的运行结果,
localstorage运行结果
对于浏览不支持localstorage,可以使用cookie来模拟localstorage,可以参见LocalStorage
session localstroage
sessionStorage的api与使用和localstorage类似,但是 sessionStorage只存在回话中,会随着窗口的关闭而关闭。
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta name="author" content="UXDC"/>
<meta name='viewport' content='initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'>
<meta name="apple-mobile-web-app-capable" content="yes"/>
<meta name="format-detection" content="telphone=no, email=no"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="Cache-Control" content="no-siteapp" />
<meta http-equiv="x-rim-auto-match" content="none">
<meta name="HandheldFriendly" content="true">
<meta name="format-detection" content="telephone=no" />
<title>滴滴企业版</title>
<script type="text/javascript">
// html localstroage
var sessionstorage = window.sessionStorage;
// set item
sessionstorage.setItem('username', 'lijincai');
sessionstorage.setItem('openid','ksjhfkjajkdfjkszdjfksad');
sessionstorage.setItem('uid','10001');
console.log(sessionstorage);
// get item
console.log(sessionstorage.getItem('username'));
// remove item
sessionstorage.removeItem('openid');
console.log(sessionstorage)
// length
console.log(sessionstorage.length);
// clear
// sessionstorage.clear();
// console.log(sessionstorage)
</script>
</head>
<body>
<div id="jqueryId">test</div>
</body>
</html>
运行结果
同域下测试