cookie如何保存对象
时间: 2024-05-05 11:16:09 浏览: 10
Cookie只能保存字符串,因此需要将对象序列化为字符串,然后再将其存储到Cookie中。常用的序列化方法有JSON序列化和字符串模板序列化。以下是使用JSON序列化的例子:
```javascript
// 将对象序列化为字符串
const obj = { name: 'John', age: 30 };
const str = JSON.stringify(obj);
// 将字符串存储到Cookie中
document.cookie = `myObj=${str}; expires=Fri, 31 Dec 9999 23:59:59 GMT`;
```
在读取Cookie时,需要将存储的字符串反序列化为对象:
```javascript
// 从Cookie中读取字符串
const cookie = document.cookie;
const startIndex = cookie.indexOf('myObj=');
if (startIndex === -1) {
// Cookie中不存在myObj
return;
}
const endIndex = cookie.indexOf(';', startIndex);
const str = cookie.substring(startIndex + 6, endIndex === -1 ? cookie.length : endIndex);
// 将字符串反序列化为对象
const obj = JSON.parse(str);
console.log(obj.name); // John
console.log(obj.age); // 30
```