如何使用 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 字串將保留一個用分號分隔的名稱=值對列表,其中名稱是 Cookie 的名稱,值是其字串值。
示例
可以嘗試執行以下程式碼來讀取 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>
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP