zoukankan      html  css  js  c++  java
  • JQuery和JS操作LocalStorage/SessionStorage的方法

    LocalStorage

    • 是对Cookie的优化
    • 没有时间限制的数据存储
    • 在隐私模式下不可读取
    • 大小限制在500万字符左右,各个浏览器不一致
    • 在所有同源窗口中都是共享的
    • 本质是在读写文件,数据多的话会比较卡(firefox会一次性将数据导入内存)
    • 不能被爬虫爬取,不要用它完全取代URL传参
    • IE7及以下不支持外,其他标准浏览器都完全支持

    SessionStorage

    • 针对一个 session 的数据存储
    • 大小限制在5M左右,各个浏览器不一致
    • 仅在当前浏览器窗口关闭前有效(适合会话验证)
    • 不在不同的浏览器窗口中共享,即使是同一个页面

     

    SessionStorage:

    存储数据:

    sessionStorage.setItem('testKey','这是一个测试的value值'); // 存入一个值

    sessionStorage['testKey'] = '这是一个测试的value值'

    读取数据:

    sessionStorage.getItem('testKey'); // => 返回testKey对应的值

    sessionStorage['testKey']; // => 这是一个测试的value值

    存储JSON:

    var userEntity = {
        name: 'tom',
        age: 22
    };
     
    // 存储值:将对象转换为Json字符串
    sessionStorage.setItem('user', JSON.stringify(userEntity));
     
    // 取值时:把获取到的Json字符串转换回对象
    var userJsonStr = sessionStorage.getItem('user');
    userEntity = JSON.parse(userJsonStr);
    console.log(userEntity.name); // => tom

     

     

    localhostStorage:

    JS下的操作方法

    • 获取键值:localStorage.getItem(“key”)
    • 设置键值:localStorage.setItem(“key”,”value”)
    • 清除键值:localStorage.removeItem(“key”)
    • 清除所有键值:localStorage.clear()
    • 获取键值2:localStorage.keyName
    • 设置键值2:localStorage.keyName = “value”

    JQ下的操作方法(JS方法前加”window.”)

    • 获取键值:window.localStorage.getItem(“key”)
    • 设置键值:window.localStorage.setItem(“key”,”value”)
    • 清除键值:window.localStorage.removeItem(“key”)
    • 清除所有键值:window.localStorage.clear()
    • 获取键值2:window.localStorage.keyName
    • 设置键值2:window.localStorage.keyName = “value”
  • 相关阅读:
    微信小程序-上传多张图片加进度条(支持预览、删除)
    php中120个内置函数
    angular6 NgModule中定义模块module
    Aliasing input/output properties
    angular6 Can't bind to 'zzst' since it isn't a known property of
    [转]DOM 中 Property 和 Attribute 的区别
    Angular6
    [转]VirtualBox 修改UUID实现虚拟硬盘复制
    pthread_create如何传递两个参数以上的参数
    linux 线程操作问题undefined reference to 'pthread_create'的解决办法(cmake)
  • 原文地址:https://www.cnblogs.com/LChenglong/p/8006197.html
Copyright © 2011-2022 走看看