쿠키 만들기
쿠키를 만드는 가장 간단한 방법은 document.cookie 개체에 문자열 값을 할당하는 것입니다. 이것은 다음과 같습니다. -
document.cookie = "key1=value1;key2=value2;expires=date";
여기서 "만료" 속성은 선택 사항입니다. 이 속성에 유효한 날짜 또는 시간을 제공하면 쿠키가 지정된 날짜 또는 시간에 만료되고 그 이후에는 쿠키 값에 액세스할 수 없습니다.
예시
다음을 시도하십시오. 입력 쿠키에 고객 이름을 설정합니다.
라이브 데모
<html>
<head>
<script>
<!--
function WriteCookie() {
if( document.myform.customer.value == "" ) {
alert("Enter some value!");
return;
}
cookievalue= escape(document.myform.customer.value) + ";";
document.cookie="name=" + cookievalue;
document.write ("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> 쿠키 읽기
쿠키를 읽는 것은 document.cookie 개체의 값이 쿠키이기 때문에 쿠키를 쓰는 것만큼 간단합니다. 따라서 쿠키에 액세스할 때마다 이 문자열을 사용할 수 있습니다. document.cookie 문자열은 세미콜론으로 구분된 name=value 쌍의 목록을 유지합니다. 여기서 name은 쿠키의 이름이고 value는 문자열 값입니다.
예시
다음 코드를 실행하여 쿠키를 읽을 수 있습니다.
라이브 데모
<html>
<head>
<script>
<!--
function ReadCookie() {
var allcookies = document.cookie;
document.write ("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];
document.write ("Key is : " + name + " and Value is : " + value);
}
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
<p> click the following button and see the result:</p>
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form>
</body>
</html>