cookie和sessionStorage 、localStorage 对比

相同点:都存储在客户端正则表达式

不一样点:1.存储大小浏览器

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

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

2.有效时间session

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

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

cookie 设置的cookie过时时间以前一直有效,即便窗口或浏览器关闭blog

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

cookie的数据会自动的传递到服务器,服务器端也能够写cookie到客户端get

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

相关文章
相关标签/搜索