首页 > 代码库 > javascript 操作cookie

javascript 操作cookie

/**

 * ++++++++++++++++++++++++

 * 设置cookie  

 * ++++++++++++++++++++++++

 * ck_name cookie 键名

 * ck_value cookie 键值

 * expire_secs 有效期(秒)

 * ck_path cookie cookie 的服务器路径

 * ck_domain 规定 cookie 的域名

 * secure 是否通过安全的 HTTPS 连接来传输 cookie

 */

function setCookie(ck_name, ck_value, expire_secs, ck_path, ck_domain, secure){

ck_path = ck_path ? ‘; path=‘ + ck_path : ‘; path=/‘;

ck_domain = ck_domain ? ‘; domain=‘ + ck_domain : ‘‘;

secure = secure ? ‘; secure‘ : ‘‘;

if(expire_secs){

var expireDate = new Date();

expireDate.setTime(expireDate.getTime() + expire_secs*1000);

var expireStr = ‘; expires=‘ + expireDate.toGMTString(); 

}else{

var expireStr = ‘‘;

}

document.cookie = ck_name + ‘=‘ + ck_value+expireStr + ck_path + ck_domain + secure;

}

/**

 * ++++++++++++++++++++++++

 * 设置多个cookie  

 * ++++++++++++++++++++++++

 * ck_name cookie 键名

 * ck_value cookie 键值

 * expire_secs 有效期(秒)

 * ck_path cookie cookie 的服务器路径

 * ck_domain 规定 cookie 的域名

 * secure 是否通过安全的 HTTPS 连接来传输 cookie

 */

function setCookies(cmap, expire_secs, ck_path, ck_domain, secure){

if(!cmap) return ;

for(var ck_name in cmap){

var ck_value = http://www.mamicode.com/cmap.ck_name;

setCookie(ck_name, ck_value, expire_secs, ck_path, ck_domain, secure)

}


/**

 * ++++++++++++++++++++++++

 * 读取cookie

 * ++++++++++++++++++++++++

 * ck_name cookie 键名

 */

function getCookie(ck_name){

for(var cookieArr = document.cookie.split(‘;‘),i = 0, ckPrefix = ck_name+‘=‘; i < cookieArr.length; i++){

/* 删除多余空格 */

for(var cookieItem = cookieArr[i];‘ ‘ == cookieItem[0];){

cookieItem = cookieItem.substring(1,cookieItem.length); 

}

if(0 == cookieItem.indexOf(ckPrefix)){

return cookieItem.substring(ckPrefix.length, cookieItem.length);

}

}

return null;

}


/**

 * ++++++++++++++++++++++++

 * 删除cookie

 * ++++++++++++++++++++++++

 * ck_name cookie 键名

 */

function delCookie(ck_name){

if(getCookie(ck_name)){

setCookie(ck_name,‘‘,-1000000);

}

}


javascript 操作cookie