浏览器存储:意思就是本地缓存信息
local Storage
示例一:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>local Storage</title> </head> <body> <h3>local Storage</h3> <button onclick="saveData()">点我保存一个数据</button> <button onclick="readData()">读取数据</button> <button onclick="delData()">删除数据</button> <button onclick="delAllData()">删除所有数据</button> </body> <script type="text/javascript"> let p = { name: '三丰', age: 18 } function saveData () { // setItem中的入参key和vaule都必须是字符串 localStorage.setItem('msg', 'hello') localStorage.setItem('msg2', 666)//会自动 tostring localStorage.setItem('person', JSON.stringify(p)) localStorage.setItem('personobj', p)//对象可不行哦 } function readData () { const p = localStorage.getItem('person') console.log('person obj==' + p) } function delData () { localStorage.removeItem('personobj') } function delAllData () { localStorage.clear() } </script> </html>
session Storage:浏览器关闭数据丢失
示例二:运行效果和示例一相同,但关闭浏览器则数据丢失
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>session Storage</title> </head> <body> <h3>session Storage</h3> <button onclick="saveData()">点我保存一个数据</button> <button onclick="readData()">读取数据</button> <button onclick="delData()">删除数据</button> <button onclick="delAllData()">删除所有数据</button> </body> <script type="text/javascript"> let p = { name: '三丰', age: 18 } function saveData () { // setItem中的入参key和vaule都必须是字符串 sessionStorage.setItem('msg', 'hello') sessionStorage.setItem('msg2', 666)//会自动 tostring sessionStorage.setItem('person', JSON.stringify(p)) sessionStorage.setItem('personobj', p)//对象可不行哦 } function readData () { const p = sessionStorage.getItem('person') console.log('person obj==' + p) } function delData () { sessionStorage.removeItem('personobj') } function delAllData () { sessionStorage.clear() } </script> </html>
总结webStorage(local Storage + session Storage)
- 存储内容一般支持5MB左右(不同浏览器可能不太相同)
- 浏览器通过window.sessionStorage或Window.localStorage属性实现本地存储机制
- 相关API:通过键值对的方式操作
- sessionStorage.setItem('key', 'value')、localStorage.setItem('key', 'value')
- sessionStorage.getItem('key')、localStorage.getItem('key')
- sessionStorage.removeItem('key')、localStorage.removeItem('key')
- sessionStorage.clear()、localStorage.clear()
- 备注:
- sessionStorage存储的内容会随着浏览器窗口的关闭而消失
- localStorage存储的内容,需要手动删除才会消失
- xxxStorage.getItem('key')获取数据,如果获取不到,则返回null
- Json.parse(null)的返回结果仍然是null
博客内容主要用于日常学习记录,内容比较随意,如有问题,还需谅解!!!