javascript cookie类实例代码

发布时间:2020-06-12编辑:脚本学堂
javascript cookie类,js设定cookie的时间是以毫秒为单位,用js脚本处理cookie信息的类。

代码:
 

复制代码 代码示例:
/*
javascript的cookie类
注:js设定cookie的时间是以毫秒为单位
*/ 
function jscookie(){ 
var cookie_life ={year:31536000,month:2592000,week:604800, 
day:86400,hour:3600,browser:0} 
this.expires = 'browser'; 
this.path = null; 
this.domain = null; 
this.secure = null; 
this.get=function(fieldname){
var regexp = window.eval("/"+fieldname+"=([//w%,]+)(|;)/"); 
var result = document.cookie.match(regexp); 
return (result?unescape(result[1]):null); 
}
this.set=function(fieldname,fieldvalue){ 
var cookie_list; 
cookie_list = fieldname+"="+escape(fieldvalue);
cookie_list += expires_param(this.expires); 
cookie_list += path_param(this.path); 
cookie_list += domain_param(this.domain); 
cookie_list += secure_param(this.secure); 
document.cookie = cookie_list; 

function expires_param(expires){ 
var tm=0; 
if(typeof(expires)=='string'){ 
if(!cookie_life[expires]) return "";
tm = cookie_life[expires]*1000;
}else if(typeof(expires)=='number'){
tm = expires*1000; 
}else{return "";} 
expires = ";expires="+new date(new date().gettime()+ tm).toutcstring(); 
return expires; 

function path_param(path){ 
if(!path) return ""; 
return (";path="+path); 

function domain_param(domain){ 
if(!domain) return ""; 
return (";domain="+domain); 

function secure_param(secure){ 
if(secure!='secure') return "";
return ";secure"; 

例子: 
 

复制代码 代码示例:
<script language="javascript"> 
ck = new jscookie(); 
ck.expires = 'browser'; 
//ck.path='/'; 
//ck.domain='.xxx.com'; 
//ck.secure = 'secure'; 
ck.set("abc","123456"); 
alert(ck.get("abc")); 
</script>