各种存储方案
作为Web开发人员,在 Web浏览器中存储数据以改善用户体验和提升Web应用程序性能是非常常见的。在大多数情况下,可供我们使用就是LocalStorage和SessionStorage。
本篇主要介绍localStorage和sessionStorage的用法详解
在HTML5之前,开发人员一般是通过使用Cookie在客户端保存一些简单的信息的。在HTML5发布后,提供了一种新的客户端本地保存数据的方法,那就是Web Storage,它也被分为:LocalStorage和SessionStorage,它允许通过JavaScript在Web浏览器中以键值对的形式保存数据。而相比Cookie有如下优点:
拥有更大的存储容量,Cookie是4k,Web Storage为5M。
操作数据相比Cookie更简单。
不会随着每次请求发送到服务端。
您可以使用浏览器window对象访问SessionStorage和LocalStorage。请看下面的示例:
sessionStorage = window.sessionStoragelocalStorage = window.localStorage
//存储一个itemlocalStorage.setItem('name','zhang')localStorage.setItem('age',18)//读取一个itemlocalStorage.getItem('name') // "zhang"localStorage.getItem('age') // "18"//get存储对象长度localStorage.length // returns 2//通过索引get对应的key名localStorage.key(0) // returns "name"//移除一个itemlocalStorage.removeItem('name')//清空存储对象localStorage.clear()

//存储一个itemsessionStorage.setItem('name','zhang')sessionStorage.setItem('age',18)//读取一个itemsessionStorage.getItem('name') // "zhang"sessionStorage.getItem('age') // "18"//get存储对象长度sessionStorage.length // returns 2//通过索引get对应的key名sessionStorage.key(0) // returns "name"//移除一个itemsessionStorage.removeItem('name')//清空存储对象sessionStorage.clear()

注意:他们都是以字符串方式进行存储的,下面我们以存储一个JavaScript对象来作为演示
let obj = {name: 'zhang',age: 18};// 需要将其转换为JSON字符串localStorage.setItem('myObj',JSON.stringify(obj));let str = localStorage.getItem('myObj');console.log(JSON.parse(str));
简单的web存储留言板
<!DOCTYPE html><html><head><meta charset="utf-8"><title>localStorage demo</title></head><body><div><h3>简单的web存储留言板</h3><textarea id="textarea"></textarea><input type="button" onclick="addInfo()" value="留言" /><input type="button" onclick="cleanInfo()" value="清除留言" /></div><script type="text/javascript">function upInfo() {if(window.localStorage){var lStorage = window.localStorage;var textarea = window.document.getElementById("textarea");var text = lStorage.getItem("text");if (text) {textarea.value = text;}else {textarea.value = "还没有留言";}}}function addInfo() {if(window.localStorage){var textarea = window.document.getElementById("textarea");var lStorage = window.localStorage;lStorage.setItem("text",textarea.value);upInfo();}}function cleanInfo() {window.localStorage.removeItem("text");upInfo();}upInfo();</script></body></html>
localStorage和sessionStorage的存储数据的语法完全相同,只是各自的生命周期不同罢了,sessionStorage存储的数据的生命周期为只保存在设置session的当前窗口和当前窗口新建的新窗口,localStorage则能永久存储直到浏览器卸载或者人为去清除。
LocalStorage和SessionStorage之间的主要区别在于浏览器窗口和选项卡之间的数据共享方式不同。
LocalStorage可跨浏览器窗口和选项卡间共享。就是说如果在多个选项卡和窗口中打开了一个应用程序,而一旦在其中一个选项卡或窗口中更新了LocalStorage,则在所有其他选项卡和窗口中都会看到更新后的LocalStorage数据。

但是,SessionStorage数据独立于其他选项卡和窗口。如果同时打开了两个选项卡,其中一个更新了SessionStorage,则在其他选项卡和窗口中不会反映出来。举个例子:假设用户想要通过两个浏览器选项卡预订两个酒店房间。由于这是单独的会话数据,因此使用SessionStorage是酒店预订应用程序的理想选择。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号