如何在 JavaScript 中建立 Cookie?
使用 Cookie 是記住和跟蹤偏好、購買情況、佣金和其他資訊的最有效方法,而這些資訊對於改善訪問者體驗或網站統計至關重要。
建立 Cookie 的最簡單方法是將字串值分配給 document.cookie 物件,如下所示。
document.cookie = "key1=value1;key2=value2;expires=date";
其中,expires 屬性是可選的。如果你在此屬性中提供有效的日期或時間,那麼 Cookie 將在給定的日期或時間過期,此後便無法訪問 Cookie 值。
注意 - Cookie 值可能不包含分號、逗號或空格。因此,你可能需要使用 JavaScript escape() 函式對值進行編碼,然後再將其儲存在 Cookie 中。如果你這樣做,當你讀取 Cookie 值時,你還必須使用相應的 unescape() 函式。
示例
你可以嘗試以下程式碼。它在輸入 Cookie 中設定了客戶名稱。
<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>
廣告