JavaScript语言: cookie操作代码
smartclick_Cookie = {
get: function(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = smartclick_Cookie.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
},
set: function(key, value, ttl, path, domain, secure) {
cookie = [key+'='+ encodeURIComponent(value),
'path='+ ((!path || path=='') ? '/' : path),
'domain='+ ((!domain || domain=='')? window.location.hostname : domain)];
if (ttl) cookie.push( 'expires='+smartclick_Cookie.hoursToExpireDate(ttl));
if (secure) cookie.push('secure');
return document.cookie = cookie.join('; ');
},
//@param integer ttl Time To Live (hours)
hoursToExpireDate: function(ttl) {
if (parseInt(ttl) == 'NaN' ) return '';
else {
now = new Date();
now.setTime(now.getTime() + (parseInt(ttl) * 60 * 60 * 1000));
return now.toGMTString();
}
},
trim: function( text ) {
return (text || "").replace( /^\s+|\s+$/g, "" );
}
}
get: function(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = smartclick_Cookie.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
},
set: function(key, value, ttl, path, domain, secure) {
cookie = [key+'='+ encodeURIComponent(value),
'path='+ ((!path || path=='') ? '/' : path),
'domain='+ ((!domain || domain=='')? window.location.hostname : domain)];
if (ttl) cookie.push( 'expires='+smartclick_Cookie.hoursToExpireDate(ttl));
if (secure) cookie.push('secure');
return document.cookie = cookie.join('; ');
},
//@param integer ttl Time To Live (hours)
hoursToExpireDate: function(ttl) {
if (parseInt(ttl) == 'NaN' ) return '';
else {
now = new Date();
now.setTime(now.getTime() + (parseInt(ttl) * 60 * 60 * 1000));
return now.toGMTString();
}
},
trim: function( text ) {
return (text || "").replace( /^\s+|\s+$/g, "" );
}
}
几点说明:
1.ttl生存期时间单位是小时。
2.get方法的原理是字符串匹配,对[key=]value的中括号部分进行匹配,优于使用正则进行匹配,正则如有特殊字符的情况会很麻烦。