ตั้งค่าคุกกี้
วิธีที่ง่ายที่สุดในการสร้างคุกกี้คือการกำหนดค่าสตริงให้กับอ็อบเจกต์ 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 คั่นด้วยเครื่องหมายอัฒภาค โดยที่ชื่อคือชื่อของคุกกี้ และค่าคือค่าสตริง
ตัวอย่าง
คุณสามารถลองเรียกใช้โค้ดต่อไปนี้เพื่ออ่านคุกกี้ −
สาธิตสด
<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>