본문 바로가기

Local Oriented/jQuery

jQuery Cookie

- Date() 의 getMonth() 는 0부터 시작하므로, 오늘이 9/7 이면 getMonth() 가 8로 나온다.




  쿠키 리셋 방법은 null 을 설정하는 것..
<script>
 $(function () {
  if ($.cookie('notice') == undefined) { // $.cookie() 는 jquery-cookie 플러그인
   $("#div1").css("display", "block");
  }
 });
 function setCookie() {
  $.cookie('notice', '1', { expires: 2 }); //숫자만큼 열지않기
  $("#div1").css("display", "none");
 }
</script>


- UTC 와 GMT
<script>
  var today = new Date();
  var utc = today.toUTCString(); // Coordinated Universal Time, atomic time
  var gmt today.toGMTString(); // Deprecated. 사용 지양. Greenwich Mean Time, 'solar' timezone
  //alert('UTC:'+utc+'\nGMT:'+gmt);
</script>


- Pure Javascript 와 jquery Plug-in 인 jquery.cookie 비교
참고로.. new Date(2017, 2, 0) 이라고 하면.. 실제로는 2017.1.31 이 됩니다. 재미있죠..?
어느 달의 마지막 일자를 찾아내는 방법으로 사용하면 좋아요. 특히 윤년을 고려한 2월 마지막 일자

<script>
  function setCookie(name, value, days){
    var date = new Date();
    date = new Date(date.getFullYear(), date.getMonth() +1, date.getDate()+days); // +1 달이 0부터 서수로 세팅
    var expires = '; expires=' + date.toUTCString();
    document.cookie = name+ '=' +value+ expires+ '; path=/';
  }

  function getCookie(name){
    var i, x, y, ARRcookies = document.cookie.split(';');
    for(i=0,s=ARRcookies.length; i<s; i++){
      x = ARRcookies[i].substr(0, ARRcookies[i].indexOf('='));
      y = ARRcookies[i].substr(ARRcookies[i].indexOf('=') +1);
      x = x.replace(/^\s+|\s+$/g, '');
      if(x==name) return unescape(y);
    }
  }

  function setCookie2(name,value,days){
    $.cookie(name, value, { expires: days });
  }
  function getCookie2(name){
    return $.cookie(name);
  }


  setCookie('test', 1, 1);
  //alert(getCookie('test'));

  setCookie2('test2', '1', '1');
  //alert(getCookie2('test2'));
</script>


*. 재미있는 이야기...

 - 웹서버를 사용하지 않고 웹브라우저에서 상기 코드가 들어 있는 .html 파일을 불러와서 실행하는 경우..

   IE 에선 쿠키값이 alert 되는 반면, Chrome 에선 undifined 가 alert.. 그래서 왜 오류가 발생하나 한참 찾아 봤지만..

   결국 웹서버를 통하지 않아 쿠키가 발생하지 않은 것.. ㅠ.