什么是 Cookie ?
在 JavaScript 中,cookie 是存储在用户 Web 浏览器中的数据片段。Cookie 存储在浏览器内的键值对中。我们可以使用 document 对象的 cookie 属性来操作 cookie。我们可以使用 cookie 属性在键值对中设置或存储 cookie。我们可以使用 document 的 cookie 属性读取 cookie,并使用解构提取所需的信息。
为什么需要 Cookie?
Web 浏览器和服务器使用 HTTP 协议进行通信,而 HTTP 是一种无状态协议。但对于商业网站,需要维护不同页面之间的会话信息。
例如,您已登录到特定网页上的特定网站。同一网站的其他网页如何知道您的状态已经完成了登录过程?在这种情况下,将使用 cookie。
在许多情况下,使用 cookie 是记住和跟踪偏好、购买、佣金以及更好的访问者体验或网站统计数据所需的其他信息的最有效方法。
有时,cookie 还用于缓存、提高网站或应用程序性能。
这个怎么运作?
您的服务器以 cookie 的形式向访问者的浏览器发送一些数据。浏览器可能会接受 cookie。如果是这样,它将作为纯文本记录存储在访客的硬盘驱动器上。现在,当访客到达您网站上的另一个页面时,浏览器会将相同的 Cookie 发送到服务器进行检索。检索后,您的服务器知道/记住之前存储的内容。
Cookie 是 5 个可变长度字段的纯文本数据记录 -
- Expires - Cookie 过期的日期。如果此项为空,则 Cookie 将在访客退出浏览器时过期。
- Domain (域名) - 您网站的域名。
- Path - 设置 Cookie 的目录或网页的路径。如果要从任何目录或页面检索 Cookie,则此字段可能为空。
- Secure − 如果此字段包含单词“安全”,则只能使用安全服务器检索 Cookie。如果此字段为空,则不存在此类限制。
- Name=Value − Cookie 以键值对的形式设置和检索
Cookie 最初是为 CGI 编程而设计的。Cookie 中包含的数据会自动在 Web 浏览器和 Web 服务器之间传输,因此服务器上的 CGI 脚本可以读取和写入存储在客户端上的 Cookie 值。
设置/存储 Cookie
JavaScript 可以使用 Document 对象的 cookie 属性来操作 Cookie。JavaScript 可以读取、创建、修改和删除适用于当前网页的 Cookie。
创建 Cookie 的最简单方法是将字符串值分配给 document.cookie 对象,如下所示。
document.cookie = "key1 = value1;key2 = value2;expires = date";
这里的 expires 属性是可选的。如果您为此属性提供有效的日期或时间,则 Cookie 将在给定的日期或时间过期,此后,将无法访问 Cookie 的值。
Cookie 字符串包含用分号分隔的键值对。
注意 − Cookie 值不能包含分号、逗号或空格。因此,您可能希望使用 JavaScript escape() 函数对值进行编码,然后再将其存储在 cookie 中。如果你这样做,你还必须在读取 cookie 值时使用相应的 unescape() 函数。
例请尝试以下操作。它在输入 Cookie 中设置客户名称。
<html>
<head>
<script type = "text/javascript">
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>
输出
现在,您的计算机有一个名为 name 的 Cookie。您可以使用多个 key = value 对(以逗号分隔)设置多个 Cookie。
读取 Cookie
读取 cookie 与编写 cookie 一样简单,因为 document.cookie 对象的值就是 cookie。因此,您可以在任何时候想要访问 cookie 时使用此字符串。document.cookie 字符串将保留一个由分号分隔的 name=value 对列表,其中 name 是 cookie 的名称,value 是其字符串值。
您可以使用 strings 的 split() 函数将字符串分解为键和值,如下所示 -
例请尝试以下示例以获取所有 Cookie。
<html>
<head>
<script type = "text/javascript">
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>
注意 − 这里的 length 是 Array 类的一个方法,它返回数组的长度。我们将在单独的章节中讨论数组。到那时,请试着消化它。
注意 − 您的计算机上可能已经设置了一些其他 Cookie。
设置 Cookie 有效期
您可以通过设置到期日期并将到期日期保存在 Cookie 中,将 Cookie 的生命周期延长到当前浏览器会话之后。这可以通过将 'expires' 属性设置为日期和时间来完成。
例请尝试以下示例。它说明了如何将 cookie 的到期日期延长 1 个月。
<html>
<head>
<script type = "text/javascript">
function WriteCookie() {
var now = new Date();
now.setMonth( now.getMonth() + 1 );
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie = "name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
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 时不会返回任何内容。为此,您只需将到期日期设置为过去的时间。
例请尝试以下示例。它说明了如何通过将 Cookie 的到期日期设置为当前日期后一个月来删除 Cookie。
<html>
<head>
<script type = "text/javascript">
function WriteCookie() {
var now = new Date();
now.setMonth( now.getMonth() - 1 );
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie = "name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
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 中的特定键值对,您可以将新的键值对分配给 document.cookie 属性。在这里,您需要确保使用的是要更新其值的相同键。
语法
请按照以下语法更新 Cookie。
document.cookie="key1=value1";
在上面的语法中,我们将更新 'key' cookie 的值。
例在下面的代码中,单击 set cookies 按钮以设置 cookie。它将设置 cartItem 的 watch 值和 price 的 10000。
之后,您可以单击“获取 cookie”按钮来观察 cookie。
接下来,您可以单击更新 cookie 按钮来更新 cookie。它会将 cartItem 值更改为 bag,并将 price 更改为 5000。
现在,再次单击 get cookies 按钮以获取更新的 cookie 值。
<html>
<body>
<p id = "output"> </p>
<button onclick = "setCookies()"> Set Cookie </button> <br> <br>
<button onclick = "updateCookies()"> Update Cookie </button> <br> <br>
<button onclick = "getCookies()"> Get Cookies </button>
<script>
let output = document.getElementById("output");
function setCookies() {
document.cookie = "cartItem=watch";
document.cookie = "price=10000";
}
function updateCookies() {
// Updating cookies
document.cookie = "cartItem=bag";
document.cookie = "price=5000";
}
function getCookies() {
//Spliting the cookie string
const allCookies = document.cookie.split("; ");
output.innerHTML = "The cookie data are : <br>";
for (const cookie of allCookies) {
const [key, value] = cookie.split("=");
if (key == "cartItem" || key == "price") {
output.innerHTML += `${key} : ${decodeURIComponent(value)} <br>`;
}
}
}
</script>
</body>
</html>