如何使用 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