如何使用 JavaScript 设置 cookie 和获取 cookie?
javascriptweb developmentfront end technology
设置 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 );
// 获取数组中的所有 cookies 对
cookiearray = allcookies.split(';');
// 现在从该数组中取出键值对
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>
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

