如何在 JavaScript 中建立和讀取 Cookie 的值?
建立 Cookie
建立 Cookie 的最簡單方法是將字串值分配給 document.cookie 物件,其類似如下 −
document.cookie = "key1=value1;key2=value2;expires=date";
此處的 “expires” 屬性是可選的。如果您使用有效日期或時間提供此屬性,那麼 Cookie 將在給定日期或時間過期,此後將無法訪問 Cookie 的值。
示例
嘗試執行以下操作。它將在輸入 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>讀取 Cookie
讀取 Cookie 和寫入 Cookie 一樣簡單,因為 document.cookie 物件的值是 Cookie。因此,您可以在任何想要訪問 Cookie 時使用此字串。document.cookie 字串會保留一個 name=value 對列表,這些對由分號分隔,其中 name 是一個 Cookie 的名稱,而 value 是其字串值。
示例
您可以嘗試執行以下程式碼來讀取 Cookie
<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>
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP