session, cookie, localStorage, sessionStorage

  • sesion: 是存储在服务器端的, 用户是看不到的
  • cookie: 存储在客户端,用户可看到
  • localStorage,sessionStorage是html5中新增的数据存储方式。

cookiedocument的一个属性,通过document.cookie可以获取所有的cookie,返回一个通过;分割的key=value字符串。

设置一个新的cookie: 通过document.cookie = str来设置一个cookie, str可以包含以下值(通过分号分割):
- key=value设置或更新cookie
- ;path=path (例如 ‘/’, ‘/mydir’) 如果没有定义,默认为当前文档位置的路径。
- ;domain=domain (例如 ‘example.com’, ‘.example.com’ (包括所有子域名),’subdomain.example.com’) 如果没有定义,默认为当前文档位置的路径的域名部分
- ;max-age=max-age-in-seconds (例如一年为60*60*24*365)
- ;expires=date-in-GMTString-format 如果没有定义,cookie会在对话结束时过期
- ;secure (cookie只通过https协议传输)

实现一个简易操作cookie的对象:

/*\
|*|  :: cookies.js ::
|*|
|*|  https://developer.mozilla.org/en-US/docs/DOM/document.cookie
|*|  Syntaxes:
|*|
|*|  * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*|  * docCookies.getItem(name)
|*|  * docCookies.removeItem(name[, path], domain)
|*|  * docCookies.hasItem(name)
|*|  * docCookies.keys()
|*|
\*/

var docCookies = {
    // 获取cookie
    getItem: function (sKey) {
        return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(
            /[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
    },
    // 设置cookie
    setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
        if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) {
            return false;
        }
        var sExpires = "";
        if (vEnd) {
            switch (vEnd.constructor) {
            case Number:
                sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
                break;
            case String:
                sExpires = "; expires=" + vEnd;
                break;
            case Date:
                sExpires = "; expires=" + vEnd.toUTCString();
                break;
            }
        }
        document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" +
            sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
        return true;
    },
    // 删除cookie
    removeItem: function (sKey, sPath, sDomain) {
        if (!sKey || !this.hasItem(sKey)) {
            return false;
        }
        document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" +
            sDomain : "") + (sPath ? "; path=" + sPath : "");
        return true;
    },
    // 是否存在cookie
    hasItem: function (sKey) {
        return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(
            document.cookie);
    },
    // 获取所有的cookie名
    keys: function () {
        var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(
            /\s*(?:\=[^;]*)?;\s*/);
        for (var nIdx = 0; nIdx < aKeys.length; nIdx++) {
            aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]);
        }
        return aKeys;
    }
};

示例:

// 添加
docCookies.setItem('cookie-1', 'test cookie', Infinity);

// 获取
docCookies.getItem('cookie-1'); // test cookie

// 检测
docCookies.hasItem('cookie-1'); // true

// 获取keys
docCookies.keys(); // ['cookie-1']

// 移除
docCookies.removeItem('cookie-1');

image
image

localStorage, sessionStorage

localStorage, sessionStorage这两个存储方式相似,它们都是Storage()构造函数的实例。不同之处在于 localStorage 里面存储的数据没有过期时间设置,而存储在 sessionStorage 里面的数据在页面会话结束时会被清除。页面会话在浏览器打开期间一直保持,并且重新加载或恢复页面仍会保持原来的页面会话。注:它们存储的值为字符串格式。

属性

Storage.length:返回一个整数,表示存储在 Storage 对象中的数据项数量。

方法

Storage.key(): 该方法接受一个数值 n 作为参数,并返回存储中的第 n 个键名。
Storage.getItem():该方法接受一个键名作为参数,返回键名对应的值。
Storage.setItem():该方法接受一个键名和值作为参数,将会把键值对添加到存储中,如果键名存在,则更新其对应的值。
Storage.removeItem():该方法接受一个键名作为参数,并把该键名从存储中删除。
Storage.clear():调用该方法会清空存储中的所有键名。

示例:

var stor = window.localStorage,
    sess = window.sessionStorage,
    infos = {
        name: 'ayguo',
        age: 24,
        address: '北京'
    };


if(stor){
    // localStorage
    stor['name'] = 'ayguo';
    stor['age'] = 24;
    stor['address'] = "北京";

    stor['infos'] = JSON.stringify(infos);

    stor.setItem('key', 'this is value');

    // sessionStorage
    sess['infos'] = JSON.stringify(infos);

}

localStorage

image

sessionStorage
image

当把这个页面关掉后,再打开一个其他的页面,在控制台中查看到localStorage中的数据还存在,而sessionStorage中的数据已不存在了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值