如何将多个键值对设置为一个 cookie? [英] How to set multiple key-value pairs to one cookie?

查看:22
本文介绍了如何将多个键值对设置为一个 cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用这一行将多个键值对一次设置为一个 cookie

I am using this line to set multiple key-value pair at once to one cookie

document.cookie="username=John Smith; test1=ew; expires=Thu, 18 Dec 2013 12:00:00 GMT; path=/";

看起来test1没有成功设置到cookie,因为当我在控制台写document.cookie时,它没有打印这个键值对.有谁知道如何设置多个键值对一个cookie?

it seemed test1 is not set to the cookie successfully, because when I write document.cookie in the console, it didn't print this key-value pair. Anyone know how to set multiple key-value pair to ONE cookie?

推荐答案

将多个键值对存储到一个 cookie 中是没有意义的,因为根据定义一个 cookie 代表一个键值对.

It does not make sense to store multiple key-value pairs into one cookie, because by definition a cookie represents one key-value pair.

我相信您不太了解document.cookie 的工作原理.它不是标准的 JS 字符串:当您设置它时,它包含的 cookie 定义附加到现有 cookie 的列表中.也就是说,您不能使用此 API 同时设置两个 cookie.

I believe you don't understand well how document.cookie works. It is not a standard JS string: when you set it, the cookie definition it contains is appended to the list of existing cookies. That is, you cannot set two cookies at the same time using this API.

您有两种解决方案:

  • 为要存储的每个键值使用 cookie:

  • Use a cookie for each key-value you want to store:

document.cookie = "myCookie=myValue";
document.cookie = "myOtherCookie=myOtherValue";

  • 使用复杂数据的自定义序列化存储单个 cookie,例如 JSON:

  • Store a single cookie with a custom serialization of your complex data, for example JSON:

    document.cookie = "myCookie=" + JSON.stringify({foo: 'bar', baz: 'poo'});
    

  • 这篇关于如何将多个键值对设置为一个 cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆