码迷,mamicode.com
首页 > 编程语言 > 详细

javascript 操作cookie

时间:2014-10-29 19:34:42      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:javascript   cookie   domain   function   

/**

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

 * 设置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 = 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

标签:javascript   cookie   domain   function   

原文地址:http://perzxg.blog.51cto.com/2101851/1569304

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!