HTML5 不同存储类型是什么
在本文中,您将了解HTML5中不同类型的Web存储。Web存储更安全,可以在客户端Web浏览器上本地存储大量数据。所有数据都以键值对的形式存储。
在HTML5中,有两种类型的Web存储API。
- localStorage
- SessionStorage
localStorage: 用于在客户端存储数据。它没有过期时间,因此LocalStorage中的数据始终存在,直到用户手动删除。
语法:
- 存储数据到Web存储中: 键和值都应该是字符串或数字。
LocalStorage.setItem("key", "value");
- 从Web存储中获取数据: 我们将传递键,它将返回值。
LocalStorage.getItem("key");
示例: 在这个示例中,我们将使用本地存储。
HTML
<!DOCTYPE html>
<html>
<head>
<style>
body {
color: green;
text-align: center;
font-size: 30px;
margin-top: 30px;
font-style: italic;
}
#data {
text-align: center;
}
</style>
</head>
<body>
<input id="name"
type="name"
placeholder="enter your name" />
<button type="submit" onClick="handleClick()">
click
</button>
<br />
<div id="data"></div>
<script>
function handleClick() {
if (typeof Storage !== "undefined") {
let name = document.getElementById("name").value;
localStorage.setItem("name", name);
document.getElementById("data").innerHTML =
"Welcome To GeeksforGeeks" + " " + localStorage.name;
} else {
alert("Sorry! your browser doesn't support Web Storage");
}
}
</script>
</body>
</html>
输出:
本地存储的数据:
我们可以清楚地看到,本地存储项以键值对的形式存储,并且您可以通过检查网页上的元素并转到 应用程序 选项,您将找到本地存储。
由于 localStorage 对象存储的数据没有过期日期,您可以通过关闭当前标签页并再次访问相同页面来交叉检查此数据,您会发现相同的数据存在于该标签页或窗口的localStorage中。
会话存储 : 它用于在客户端存储数据。会话存储中的数据存在于当前标签页打开的时间,如果关闭当前标签页,我们的数据也将自动从会话存储中删除。
语法:
- 用于在web存储中存储数据:
SessionStorage.setItem("key", "value");
- 获取网络存储中的数据:
SessionStorage.getItem("key");
示例: 在这个示例中,我们将使用会话存储
HTML
<!DOCTYPE html>
<html>
<head>
<style>
body {
color: green;
text-align: center;
font-size: 30px;
margin-top: 30px;
font-style: italic;
}
#data {
text-align: center;
}
</style>
</head>
<body>
<input id="name"
type="name"
placeholder="enter your name">
<button type="submit" onClick="handleClick()">
click
</button>
<br>
<div id="data"></div>
<script>
function handleClick() {
if (typeof (Storage) !== "undefined") {
let name = document.getElementById("name").value;
sessionStorage.setItem("name", name);
document.getElementById("data").innerHTML =
("Welcome To GeeksforGeeks" + " " + sessionStorage.name);
}
else {
alert("Sorry! your browser is not supporting the browser")
}
}
</script>
</body>
</html>
结果:
会话存储中的数据:
由于sessionStorage对象会将数据存储带有过期日期,您可以通过关闭当前标签页并再次访问同一页面来进行交叉检查,您会发现该标签页或窗口的sessionStorage中的数据为空。