首页 > 代码库 > Cookie操作

Cookie操作

Cookie每个域个数、大小限制

Cookie设置、删除、获取

/*
 * @param  name{string}          设置cookie名
 * @param  value{string}         设置cookie值
 * @param  options{object}       设置其他配置参数
 *
 * options.expires               过期时间(ms)
 * options.path                  路径
 * options.domain                域名
 * options.secure                secure值为true时,在http中无效,在https中有效
 */


function
Cookie(name, value, options){ if(typeof value != ‘undefined‘){ options = options || {}; if(value =http://www.mamicode.com/== null){ options.expires = -1; //过期 } var expires = ‘‘; //存在时间选项 if(options.expires && (typeof options.expires == ‘number‘ || options.expires.toUTCString)){ var date; if(typeof options.expires == ‘number‘){ date = new Date(); date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); }else{ date = options.expires; } expires = ‘; expires=‘+date.toUTCString(); } var path = options.path ? ‘; path=‘+options.path : ‘‘; var domain = options.domain ? ‘; domain=‘+options.domain : ‘‘; var secure = options.secure ? ‘; secure‘ : ‘‘; //写入cookie document.cookie = [name, ‘=‘, encodeURIComponent(value), expires, path, domain, secure].join(‘‘); }else{//读取cookie var cookValue = http://www.mamicode.com/null; if(document.cookie && document.cookie != ‘‘){ var cookie = document.cookie.split(‘;‘); for(var i = 0, len = cookie.length; i < len; i++){ var cookie = cookie[i].replace(/^\s+|\s+$/g, ‘‘); if(cookie.substring(0, name.length + 1) == (name + ‘=‘)){ cookValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookValue; }}
//设置Cookie("user", "小七");//获取Cookie("user");//删除Cookie("user", null);

 

Cookie操作