如何在 JavaScript 中获取与文档关联的 Cookie?
在本文中,我们将学习如何在 JavaScript 中获取与文档关联的 Cookie。
Document 接口中提供的 cookies 属性用于在 JavaScript 中返回与 Document 关联的 Cookie。Cookie 是存储在浏览器中以 **名称=值** 对形式存在的小型数据字符串。每个 Cookie 都用 **';'** 分隔。
Cookie 用于客户端-服务器应用程序。Cookie 有一个过期日期。它们的大小限制为 4KB。
为了更好地理解这个概念,让我们在本文中进一步研究示例。
语法
获取文档中关联的 Cookie 的语法如下所示。
document.cookie;
示例 1
以下是一个示例程序,我们在其中显示了文档中存在的 Cookie。
<html>
<body>
<p id="cookie"></p>
<script>
document.getElementById("cookie").innerHTML = "Cookies associated with this document: " + document.cookie;
</script>
</body>
</html>
执行上述代码后,将生成以下输出。
示例 2
下面的程序是显示文档中存在的 Cookie 的示例。
<!DOCTYPE html>
<html>
<head>
<title>To display the domain of the server that loaded a document in JavaScript</title>
</head>
<body style="text-align : center">
<h3>To display the domain of the server that loaded a document in JavaScript</h3>
<p id='cookies'></p>
<script>
document.getElementById('cookies').innerHTML = 'The cookies associated in this document are : '+document.cookie ;
</script>
</body>
</html>
执行上述代码后,将生成以下输出。
示例 3
下面是一个示例程序,用于创建用户定义的 Cookie。即设置和获取 Cookie,最后显示 Cookie。
<!DOCTYPE html>
<html>
<head>
<title>To display the domain of the server that loaded a document in JavaScript</title>
</head>
<body style="text-align : center">
<h3>To display the domain of the server that loaded a document in JavaScript</h3>
<p id='cookies'></p>
<script>
document.cookie = "username= John Nicholas; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/"; // Set the cookie
let x = document.cookie; // Get the cookie
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; // Delete the cookie by not specifying any value and set the expires value to past date.
document.getElementById('cookies').innerHTML = 'The cookies associated in this document are : '+document.cookie ;
</script>
</body>
</html>
执行上述代码后,将生成以下输出。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP