zoukankan      html  css  js  c++  java
  • cookie和sessionStorage 、localStorage 对比

    相同点:都存储在客户端

    不同点:1.存储大小

    cookie数据大小不能超过4k。

    sessionStorage和localStorage 虽然也有存储大小的限制,但比cookie大得多,可以达到5M或更大。

    2.有效时间

    localStorage 存储持久数据,浏览器关闭后数据不丢失除非主动删除数据;

    sessionStorage 数据在当前浏览器窗口关闭后自动删除。

    cookie 设置的cookie过期时间之前一直有效,即使窗口或浏览器关闭

    3. 数据与服务器之间的交互方式

    cookie的数据会自动的传递到服务器,服务器端也可以写cookie到客户端

    sessionStorage和localStorage不会自动把数据发给服务器,仅在本地保存。

    cookie操作

    JS设置cookie

    document。cookie="name="+username;

    function setCookie(name,value){  
      var Days=30;
      var exp=new Date();
      exp.setTime(exp.getTime()+Days*24*60*60*1000);        
      document.cookie=name+"="+escape(value)+";expires="+exp.toGMTString();  
    }

    读取cookies

    1.使用正则表达式

    function getCookie(name)
    {
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg))
    return unescape(arr[2]);
    else
    return null;
    }

    2.截取字符串读取cookie

    function getCookie(key) {
        var data = document.cookie;
        var findStr = key + "=";
    //找到key的位置
        var index = data.indexOf(findStr);
        if (index == -1)
            return null;
        var subStr = data.substring(index +findStr.length);
        var lastIndex = subStr.indexOf(";");
        if (lastIndex == -1) {
            return subStr;
        } else {
            return subStr.substring(0,lastIndex);
        }
    }    

    3.使用正则表达式+JSON

    function getCookie(key) {
        return JSON.parse("{"" +document.cookie.replace(/;s+/gim,         "","").replace(/=/gim, "":"") + ""}")[key];
    }

    清除Cookie

    function deleteCookie(name) {

      var expdate = new Date(); 
      expdate.setTime(expdate.getTime() - (86400 * 1000 * 1)); 
      setCookie(name, "", expdate); 
    }

     

  • 相关阅读:
    Spring.profile配合Jenkins发布War包,实现开发、测试和生产环境的按需切换
    Ubuntu 配置 Tomcat
    Proper usage of Java -D command-line parameters
    Linux下设置MySql自动启动
    cent6.x配置主机名及静态网络
    vmware can not be closed virtual machine is busy
    VMware虚拟机下扩容磁盘(centos7)
    Spring、MyBatis、Shiro、Quartz、Activiti框架
    Jenkins ChangeLog
    JEECG DataGridColumn dictionary使用问题
  • 原文地址:https://www.cnblogs.com/littlewriter/p/6704487.html
Copyright © 2011-2022 走看看