2009/02/25

cookie读写类

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, "" );
    }
}

几点说明:
1.ttl生存期时间单位是小时。
2.get方法的原理是字符串匹配,对[key=]value的中括号部分进行匹配,优于使用正则进行匹配,正则如有特殊字符的情况会很麻烦。

2 条评论:

  1. 阿彪,介绍几个你们学校的网站高手给我,我弄个小站

    回复删除
  2. 还有,你这个发表评论的插件在ff下很不友好啊。。。半天出不来字母。。对网友太不友好了,撤了这插件吧

    回复删除