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

วิธีตั้งค่า Cookies ให้หมดอายุใน 1 ชั่วโมง ด้วย JavaScript

สามารถขยายอายุ Cookie เกิน Session ปัจจุบันได้โดยตั้งค่า Expiration Date และบันทึกไว้ใน Cookie ใช้ Attribute expires ตั้งค่าวันที่และเวลา

ตัวอย่าง

<html> 
  <head> 
    <script> 
      function WriteCookie() { 
        var now = new Date(); 
        now.setTime(now.getTime() + 1 * 3600 * 1000); 
        cookievalue = escape(document.myform.customer.value) + ";"; 
        document.cookie = "name=" + cookievalue; 
        document.cookie = "expires=" + now.toUTCString() + ";"; 
        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>