cookie具体使用的代码
时间: 2024-12-13 13:18:00 浏览: 4
在JavaScript中,你可以使用`document.cookie` API 来操作cookie。下面是一些基本的cookie操作示例:
```javascript
// 设置一个新的cookie
setCookie('key', 'value', { expires: 7, path: '/' });
function setCookie(name, value, options = {}) {
let expires = '';
if (options.expires) {
const days = options.expires;
const date = new Date();
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
expires = '; expires=' + date.toUTCString();
}
document.cookie = `${name}=${encodeURIComponent(value)}${expires}; ${options.path ? `path=${options.path}` : ''}${options.domain ? `domain=${options.domain}` : ''}${options.secure ? '; secure' : ''}`;
}
// 获取cookie值
function getCookie(name) {
const nameEQ = `${name}=`;
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
let cookie = cookies[i];
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1);
}
if (cookie.indexOf(nameEQ) === 0) {
return decodeURIComponent(cookie.substring(nameEQ.length));
}
}
return null;
}
// 删除cookie
function deleteCookie(name) {
setCookie(name, '', { expires: -1 });
}
```
阅读全文