cookie储存

Cookie



用于储存Web页面用户信息

什么是 Cookie?



Cookie 是一些数据, 存储于你电脑上的文本文件中。

当 web 服务器向浏览器发送 web 页面时,在连接关闭后,服务端不会记录用户的信息。

Cookie 的作用就是用于解决 "如何记录客户端的用户信息":

  • 当用户访问 web 页面时,他的名字可以记录在 cookie 中。

  • 在用户下一次访问该页面时,可以在 cookie 中读取用户访问记录。

Cookie 以名/值对形式存储,如下所示:

username=John Doe

当浏览器从服务器上请求 web 页面时, 属于该页面的 cookie 会被添加到该请求中。服务端通过这种方式来获取用户的信息。


javascript中使用document.cookie属性来创建 、读取、及删除 cookie。

 

 



获取

document.cookie;


删除

document.cookie = "a=; expires=Thu, 01 Jan 1970 00:00:01 GMT";

 

设置

// 关闭页面失效
document.cookie = "a=1; b=2";

// 一周后失效
var d = new Date();
d.setTime(d.getTime() + 7 * 24 * 60 * 60 * 1000);
document.cookie = "c=3; expires=" + d.toUTCString();

// 当前页面有效
document.cookie = "a=1; path=/";



封装成函数,便于调用


/**
 * [setCookie 添加单个cookie]
 * @param {String} key     [cookie名]
 * @param {String} value   [cookie值]
 * @param {String} expires [有效时间]
 * @param {String} path    [cookie路径]
 */
function setCookie(key = '', value = '', expires = '', path='') {
    if(expires) {
        var d = new Date();
        var t = 24 * 60 * 60 * 1000;
        if(~expires.indexOf('m')) t = 60 * 1000;                //
        if(~expires.indexOf('h')) t = 60 * 60 * 1000;           //
        if(~expires.indexOf('d')) t = 24 * 60 * 60 * 1000;      //
        if(~expires.indexOf('D')) t = 7 * 24 * 60 * 60 * 1000;  //
        if(~expires.indexOf('M')) t = 30 * 24 * 60 * 60 * 1000; //
        if(~expires.indexOf('Y')) t = 365 * 24 * 60 * 60 * 1000;//
        d.setTime(d.getTime() + (parseInt(expires) * t));
        var expires = "; expires=" + d.toUTCString();
    }
    if(path) path = '; path='+path;
    document.cookie = key + '='+value+expires+path;
}

/**
 * [getCookie 获取cookie]
 * @param  {[type]} key [cookie名]
 * @return {[type]}     [cookie值]
 */
function getCookie(key) {
    var coo = document.cookie;
    var cooArr = coo.split(';');
    for(var i = 0; i < cooArr.length; i++) {
        var c = cooArr[i].trim().split('=');
        if(c[0] == key) {
            return c[1];
        }
    }
}

/**
 * [removeCookie 删除cookie]
 * @param  {[type]} key [cookie名]
 * @return {[type]}     [无]
 */
function removeCookie(key) {
    document.cookie = key+'=; expires=Thu, 01 Jan 1970 00:00:00 GMT';
}

/**
 * [setCookies 设置cookie,可多个,不可以设置有效日期和cookie路径]
 * @param {[Object]} obj [要储存的cookie的键值对]
 */
function setCookies(obj) {
    if (!~arr.constructor.toString().indexOf('Object'))
        throw ('参数只能是数组!');
    for(var i in obj) {
        setCookie(i, obj[i]);
    }
}

/**
 * [removeCookies 删除cookie,可多个,数组参数]
 * @param  {[Array]} arr [要删除的cookie名数组]
 * @return {[type]}     [无]
 */
function removeCookies(arr) {
    if(!~arr.constructor.toString().indexOf('Array'))
        throw('参数只能是数组!');
    for (var i in arr) {
        removeCookie(arr[i]);
    }
}

 我的博客

猜你喜欢

转载自www.cnblogs.com/seeks/p/10177129.html