Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีสร้าง Cookies ใน JavaScript

Cookies เป็นวิธีที่มีประสิทธิภาพที่สุดในการจดจำและติดตาม Preferences, Purchases, Commissions และข้อมูลอื่นๆ เพื่อประสบการณ์ผู้ใช้ที่ดีขึ้นหรือสถิติเว็บไซต์

วิธีง่ายที่สุดคือกำหนดค่าสตริงให้ document.cookie ดังนี้

document.cookie = "key1=value1;key2=value2;expires=date";

Attribute expires เป็นทางเลือก หากระบุวันที่/เวลาที่ถูกต้อง Cookie จะหมดอายุในวันนั้น และค่าจะเข้าถึงไม่ได้

หมายเหตุ - ค่า Cookie ห้ามมี Semicolon, Comma, หรือ Whitespace ควรใช้ escape() เข้ารหัสก่อนเก็บ และ unescape() ถอดรหัสเมื่ออ่าน

ตัวอย่าง

<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>