쿠키생성 (1)

이번에는 쿠키를 다루는 방법에 대해서 알아보도록 하겠습니다. ^___^

Cookies 만들기

문법부터 보도록 하겠습니다.
document.cookie = "key1=value1;key2=value2;expires=date";

여기서 expires 속성은 옵션입니다. 쿠키의 생명주기를 지정해주는 속성이죠. 지정된 시일이 지나면 쿠키는 더이상 유효하지 않게됩니다.

Note: 쿠키 값은 세미콜론이나 쉼표 또는 스페이스를 포함할 수 없습니다. 그래서 저장하기 전에 escape() 함수를 이용해서 인코딩한 값을 이용하기도 하죠. escape()함수로 인코딩해서 저장을 했을 때는 unescape() 함수를 이용해서 decode해야 쿠키값을 제대로 읽어올 수 있습니다.

 

 

아래 예제는 input쿠키에 customer의 이름을 저장하는 것을 보여주고있습니다.

<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
   if( document.myform.customer.value == "" ){
      alert("Enter some value!");
      return;
   }

   cookievalue= escape(document.myform.customer.value) + ";";
   document.cookie="name=" + cookievalue;
   alert("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>
</form>
</body>
</html>

Cookies 읽기

​자바스크립트에서 쿠키는 document.cookie 객체라는 것은 위에서 알게되셨을겁니다. 쿠키에는 key, value페어가 여러개가 들어가있을 수 있습니다. 그리고 key와 value는 각각 세미콜론으로 구분이 되어집니다. 따라서 쿠키를 읽을때는 split() 함수를 사용하게 됩니다.

 

 

예제를 한번 보시죠.

<html>
<head>
<script type="text/javascript">
<!--
function ReadCookie()
{
   var allcookies = document.cookie;
   alert("All Cookies : " + allcookies );

   // Get all the cookies pairs in an array
   cookiearray  = allcookies.split(';');

   // Now take key value pair out of this array
   for(var i=0; i<cookiearray.length; i++){
      name = cookiearray[i].split('=')[0];
      value = cookiearray[i].split('=')[1];
      alert("Key is : " + name + " and Value is : " + value);
   }
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form>
</body>
</html>

 

 

위 소스는 여러분 컴퓨터에 저장된 쿠키를 읽어들여서 키, 값 페어를 화면에 출력하게됩니다. 

직접 한번 실행해 보세요~~ ^__^ 

Cookies 만료일자 설정하기

예제로 배워봅시다~~ 아래 예제는 쿠키의 만료일자를 1달뒤로 설정하는 코드입니다.

 

<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
   var now = new Date();
   now.setMonth( now.getMonth() + 1 ); 
   cookievalue = escape(document.myform.customer.value) + ";"
   document.cookie="name=" + cookievalue;
   document.cookie = "expires=" + now.toUTCString() + ";"
   alert("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>

Cookie 삭제하기

삭제를 하는 것은 실제로 삭제를 하는것이 아니라 단지 만료일자를 과거일자로 세팅하는 것입니다.

아래 예제를 보실까요?


<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
   var now = new Date();
   now.setMonth( now.getMonth() - 1 ); 
   cookievalue = escape(document.myform.customer.value) + ";"
   document.cookie="name=" + cookievalue;
   document.cookie = "expires=" + now.toUTCString() + ";"
   alert("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>

 

 

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_cookies.htm