본문 바로가기

컴터/jQuery

[jQuery] Cookie 플러그인

http://plugins.jquery.com/node/5774


(function($){
 $.cookie = function(key, value, options) {
  if(arguments.length > 1) {
   var o = $.extend({}, $.cookie.defaults, options);
         if (value === null || value === undefined) {
             value = '';
             o.expires = -1;
         }
         if (o.expires.constructor != Date) {
    var today = new Date();
    today.setDate(today.getDate() + o.expires);
    o.expires = today;
   }
   // Create the cookie string
   document.cookie =
    key + '=' + value +
    '; expires=' + o.expires.toUTCString() +
    (o.path? '; path=' + (o.path) : '') +
    (o.domain? '; domain=' + (o.domain) : '') +
    (o.secure? '; secure' : '');
  } else {
   if(result = new RegExp(key+"=(.*?)(?:;|$)").exec(document.cookie))
    return decodeURIComponent(result[1]);
   return false;
  }
 };
 $.cookie.defaults = {
  expires: 365,
  path: '/'
 }
})(jQuery);

사용법 : $.cookie(키, 값, 옵션);
옵션은 {expires:'',domain:'', path:'', secure:''}

 예 : $.cookie('key', 'ok', {expires:7,domain:'.myhost.com', path:'/', secure:0});
 expires는 日단위..


뽑아오기 : alert($.cookie('happy_new_expire'));

태그