前端如何将数据存储到Cookie里
时间: 2024-09-19 16:16:17 浏览: 32
前端Cookie工具,获取Cookie数据,获取Cookie数据key名称,清除站点所有Cookie数据
前端JavaScript可以使用`document.cookie` API 来操作Cookie。以下是设置、读取和删除Cookie的基本步骤:
1. **设置Cookie** (Set Cookie):
```javascript
function setCookie(name, value, days) {
var expires = '';
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toUTCString();
}
document.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/';
}
// 示例:设置一个名为"username",值为"JohnDoe",有效期1天的Cookie
setCookie('username', 'JohnDoe', 1);
```
2. **读取Cookie** (Get Cookie):
```javascript
function getCookie(name) {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookiePair = cookies[i].trim();
if (cookiePair.indexOf(name + '=') === 0) {
return decodeURIComponent(cookiePair.slice(name.length + 1));
}
}
return null;
}
// 示例:获取名为"username"的Cookie值
var username = getCookie('username');
```
3. **删除Cookie** (Delete Cookie):
```javascript
function deleteCookie(name) {
document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
}
// 示例:删除名为"username"的Cookie
deleteCookie('username');
```
阅读全文