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

查看:756
本文介绍了如何将多个键值对设置为一个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天全站免登陆