简体   繁体   English

如何在Javascript中解析一个Cookie中的多个值

[英]How to parse Multiple Values in one Cookie in Javascript

I have a cookie that stores 5 values separated by commas in one cookie. 我有一个cookie,它在一个cookie中存储5个用逗号分隔的值。 I'm able to retrieve the value of ExampleCookie as follows (as example): 我可以按以下方式检索ExampleCookie的值(例如):

var CookieValue = readCookie('ExampleCookie'); var CookieValue = readCookie('ExampleCookie'); //returns Foo,Bar,Foo1,FooFighter,Bar2 //返回Foo,Bar,Foo1,FooFighter,Bar2

How do I parse through CookieValue to assign individual variables such that I can assign a variable to each of the 5 parts? 如何通过CookieValue解析以分配单个变量,以便可以将变量分配给5个部分中的每个部分?

I've found ways to do this with PHP but not javascript. 我找到了用PHP而不是javascript做到这一点的方法。

Thanks in advance for any advice. 在此先感谢您的任何建议。

use the String.split(delimiter) method 使用String.split(delimiter)方法

var array = readCookie('ExCook').split(",");

Reference: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split 参考: https : //developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split

You need to make an array from string: 您需要根据字符串创建一个数组:

CookieParams = CookieValue.split(",");
CookieParams[0] = Foo
CookieParams[1] = Bar

You could split the CookieValue into individual values in an array via the the split() method. 您可以通过split()方法将CookieValue拆分为数组中的各个值。

var valList = CookieValue.split(','); var valList = CookieValue.split(','); // ["Foo", "Bar", "Foo1", "FooFighter", "Bar2"] // [“ Foo”,“ Bar”,“ Foo1”,“ FooFighter”,“ Bar2”]

If you then want the values to be assigned to individual variables, you would need to loop through the array and manually make the assignment. 如果然后希望将值分配给各个变量,则需要遍历数组并手动进行分配。

JSON.stringify, and JSON.parse are your best cleanest bets (imho) JSON.stringify和JSON.parse是您最好的选择(imho)

var values = JSON.parse(readCookie('ExampleCookie'));

createCookie('ExampleCookie',JSON.stringify(values));

This has the added benefit of being able to set key values in your object/array. 这样做还有一个好处,就是可以在对象/数组中设置键值。

Assuming you're using the functions found at quirks mode just ensure your cookie values stringified don't go over the 4000 char limit found in most browsers. 假设您使用的是在怪癖模式下找到的函数,只需确保已字符串化的cookie值不超过大多数浏览器中的4000个字符限制即可

I quickly realized this was more of a question on Split than about cookies. 我很快意识到,这是Split上的一个问题,而不是Cookie。 Here is what i came up w/. 这是我想出的东西。

var splits = ExampleCookie.split(","); 
var slot1 = splits[0]; 
var slot2 = splits[1]; 
var slot3 = splits[2]; etc.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM