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); 
}

 

原文地址:https://www.cnblogs.com/littlewriter/p/6704487.html