【发布时间】:2011-05-27 02:37:21
【问题描述】:
是否可以使用数组创建 cookie?
我想用 JavaScript 将 a[0]='peter'、a['1']='esther'、a['2']='john' 存储在 cookie 中。
【问题讨论】:
-
鉴于数组的性质,cooke(大小有限)是我尝试存储的最后一个位置/我尝试使用的最后一个存储方法。
标签: javascript cookies
是否可以使用数组创建 cookie?
我想用 JavaScript 将 a[0]='peter'、a['1']='esther'、a['2']='john' 存储在 cookie 中。
【问题讨论】:
标签: javascript cookies
Cookie 只能保存字符串。如果你想模拟一个数组,你需要对其进行序列化和反序列化。
您可以使用 JSON 库来做到这一点。
【讨论】:
使用 jQUery 在 cookie 中创建数组?
var list = new cookieList("test"); $(img).one('click', function(i){ while($('.selected').length < 3) {
$(this).parent()
.addClass("selected")
.append(setup.config.overlay);
//$.cookie(setup.config.COOKIE_NAME, d, setup.config.OPTS);
var index = $(this).parent().index();
// suppose this array go into cookies.. but failed
list.add( index );
var count = 'You have selected : <span>' + $('.selected').length + '</span> deals';
if( $('.total').length ){
$('.total').html(count);
}
} });
【讨论】:
我同意其他 cmets - 你不应该这样做,你应该使用 JSON。但是,要回答您的问题,您可以通过将数组存储为逗号分隔的字符串来解决这个问题。假设您想将以下 Javascript 数组保存到 cookie 中:
var a = ['peter','esther','john'];
你可以定义一个 cookie 字符串,然后遍历数组:
// Create a timestamp in the future for the cookie so it is valid
var nowPreserve = new Date();
var oneYear = 365*24*60*60*1000; // one year in milliseconds
var thenPreserve = nowPreserve.getTime() + oneYear;
nowPreserve.setTime(thenPreserve);
var expireTime = nowPreserve.toUTCString();
// Define the cookie id and default string
var cookieId = 'arrayCookie';
var cookieStr = '';
// Loop over the array
for(var i=0;i<a.length;i++) {
cookieStr += a[i]+',';
}
// Remove the last comma from the final string
cookieStr = cookieStr.substr(0,cookieStr.length-1);
// Now add the cookie
document.cookie = cookieId+'='+cookieStr+';expires='+expireTime+';domain='+document.domain;
在本例中,您将存储以下 cookie(如果您的域是 www.example.com):
arrayCookie=peter,ester,john;expires=1365094617464;domain=www.example.com
【讨论】:
正如您在topic 中看到的那样:
你结合使用jQuery.cookie插件和JSON来解决你的问题。
当你要存储一个数组时,你在JS中创建一个数组并使用JSON.stringify将其转换为字符串并使用$.cookie('name', 'array_string')存储
var myAry = [1, 2, 3];
$.cookie('name', JSON.stringify(myAry));
当您想要检索 cookie 中的数组时,您使用 $.cookie('name') 检索 cookie 值并使用 JSON.parse 从字符串中检索数组。
var storedAry = JSON.parse($.cookie('name'));
//storedAry -> [1, 2, 3]
【讨论】:
我将 Script 下面的代码(参见下面的代码)添加到一个名为 CookieMonster.js 的 javascript 文件中。
它是来自 http://www.quirksmode.org/js/cookies.html 的当前 sn-p 的包装器
它适用于数组和字符串,它会自动转义数组/字符串的逗号, 和分号;(原始sn-ps 中未处理)。
我已经列出了我内置的简单用法和一些奖励用法。
用法:
//set cookie with array, expires in 30 days
var newarray = ['s1', 's2', 's3', 's4', 's5', 's6', 's7'];
cookiemonster.set('series', newarray, 30);
var seriesarray = cookiemonster.get('series'); //returns array with the above numbers
//set cookie with string, expires in 30 days
cookiemonster.set('sample', 'sample, string;.', 30);
var messagestring = cookiemonster.get('sample'); //returns string with 'sample, string;.'
奖金:
//It also conveniently contains splice and append (works for string or array (single string add only)).
//append string
cookiemonster.append('sample', ' add this', 30); //sample cookie now reads 'sample, string;. add this'
//append array
cookiemonster.append('series', 's8', 30); //returns array with values ['s1', 's2', 's3', 's4', 's5', 's6', 's7', 's8']
//splice
cookiemonster.splice('series', 1, 2, 30); //returns array with values ['s1', 's4', 's5', 's6', 's7', 's8']
CookieMonster.js:
var cookiemonster = new Object();
cookiemonster.append = function (cookieName, item, expDays) {
item = cm_clean(item);
var cookievalue = cookiemonster.get(cookieName);
if (cookievalue instanceof Array) {
cookievalue[cookievalue.length] = item;
cm_createCookie(cookieName, cm_arrayAsString(cookievalue), expDays);
} else {
cm_createCookie(cookieName, cookievalue + item, expDays);
}
};
cookiemonster.splice = function (cookieName, index, numberToRemove, expDays) {
var cookievalue = cookiemonster.get(cookieName);
if (cookievalue instanceof Array) {
cookievalue.splice(index, numberToRemove);
cm_createCookie(cookieName, cm_arrayAsString(cookievalue), expDays);
}
};
cookiemonster.get = function (cookieName) {
var cstring = cm_readCookie(cookieName);
if (cstring.indexOf('<#&type=ArrayVals>') != -1) {
var carray = cstring.split(',');
for (var i = 0; i < carray.length; i++) {
carray[i] = cm_dirty(carray[i]);
}
if (carray[0] == '<#&type=ArrayVals>') {
carray.splice(0, 1);
}
return carray;
} else {
return cm_dirty(cstring);
}
};
cookiemonster.set = function (cookieName, value, expDays) {
if (value instanceof Array) {
cm_createCookie(cookieName, cm_arrayAsString(value), expDays);
}
else { cm_createCookie(cookieName, cm_clean(value), expDays); }
};
cookiemonster.eraseCookie = function (name) {
cm_createCookie(name, "", -1);
};
function cm_replaceAll(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
};
function cm_clean(ret) {
ret = cm_replaceAll(ret.toString(), ',', ',');
ret = cm_replaceAll(ret.toString(), ';', ';');
return ret;
};
function cm_dirty(ret) {
ret = cm_replaceAll(ret, ',', ',');
ret = cm_replaceAll(ret, ';', ';');
return ret;
};
function cm_createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
} else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
};
function cm_readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
};
function cm_arrayAsString(array) {
var ret = "<#&type=ArrayVals>"; //escapes, tells that string is array
for (var i = 0; i < array.length; i++) {
ret = ret + "," + cm_clean(array[i]);
}
return ret;
};
【讨论】:
对于这个例子,你可以很容易地做到这一点:
制作 Cookie:
///W3Schools Cookie Code:
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
///My Own Code:
for(a=0;a<b.length;a++){
setCookie(b[a],b[a],periodoftime);
}
检索数组:
for(a=0;a<b.length;a++){
b[a] = getCookie(b[a])
}
对于除字符串之外还有其他值类型的数组:
制作饼干:
///Replace MyCode above With:
if(typeof b[a] === 'string'){
setCookie(b[a],b[a],periodoftime);
}else{
setCookie(b[a].toString,b[a],periodoftime);
}
检索数组:
for(a=0;a<b.length;a++){
if(typeof b[a] === 'string'){
b[a] = getCookie(b[a])
}else{
b[a] = getCookie(b[a].toString)
}
}
唯一的缺陷是无法检索相同的值。
不需要 JQuery、逗号分隔或 JSON。
【讨论】:
我创建了这种获取 cookie 的简单方法。在这里执行会报错,但是可以正常使用
var arrayOfCookies = [];
function parseCookieToArray()
{
var cookies = document.cookie;
var arrayCookies = cookies.split(';');
arrayCookies.map(function(originalValue){
var name = originalValue.split('=')[0];
var value = originalValue.split('=')[1];
arrayOfCookies[name] = value;
});
}
console.log(arrayOfCookies); //in my case get out: [language: 'en_US', country: 'brazil']
parseCookieToArray();
新
我的新 obj 到 create get cookies
cookie = {
set: function(name, value) {
document.cookie = name+"="+value;
},
get: function(name) {
cookies = document.cookie;
r = cookies.split(';').reduce(function(acc, item){
let c = item.split('='); //'nome=Marcelo' transform in Array[0] = 'nome', Array[1] = 'Marcelo'
c[0] = c[0].replace(' ', ''); //remove white space from key cookie
acc[c[0]] = c[1]; //acc == accumulator, he accomulates all data, on ends, return to r variable
return acc; //here do not return to r variable, here return to accumulator
},[]);
}
};
cookie.set('nome', 'Marcelo');
cookie.get('nome');
【讨论】:
为 cookiemonster 添加了删除功能
// remove item
cookiemonster.remove('series', 's6', 30); //returns array with values ['s1', 's2', 's3', 's4', 's5', 's7', 's8']
cookiemonster.remove = function (cookieName, item, expDays) {
var cookievalue = cookiemonster.get(cookieName);
//Find the item
for( var i = 0; i < cookievalue.length; i++) {
if ( cookievalue[i] === item) {
cookievalue.splice(i, 1);
}
}
cm_createCookie(cookieName, cm_arrayAsString(cookievalue), expDays);
};
【讨论】:
您可以在一个 cookie 中保存大量数据并将其作为数组返回,试试这个
function setCookie(cookieKey, cookieValue) {
var cookie = document.cookie.replace(/(?:(?:^|.*;\s*)idpurchase\s*\=\s*([^;]*).*$)|^.*$/, "$1")
var idPurchase = cookie.split(",")
idPurchase.push(cookieValue)
document.cookie = cookieKey+"=" + idPurchase
console.log("Id das compras efetuadas :",idPurchase)
$("#purchases_ids option:last").after($('<option onclick="document.getElementById("input_class1").value='+cookieValue+'" value="'+cookieValue+'">'+cookieValue+'</option>'))
}
checkCookie()
function checkCookie() {
var cookie = document.cookie.replace(/(?:(?:^|.*;\s*)idpurchase\s*\=\s*([^;]*).*$)|^.*$/, "$1")
var idPurchase = cookie.split(",")
console.log("Id das compras efetuadas :",idPurchase)
for (i = 1; i < idPurchase.length; i++) {
$("#purchases_ids option:last").after($('<option value="'+idPurchase[i]+'">'+idPurchase[i]+'</option>'))
}
purchases_ids.addEventListener("change",changeSpeed)
}
在我创建的这个项目中,我将值存储在数组中,codePen不允许存储cookie,但在下面的示例中你可以得到一个完整的图片,只需研究实现
【讨论】:
这是以数组格式添加 cookie 的最简单形式。
function add_to_cookie(variable, value) {
var d = new Date();
d.setTime(d.getTime() + (90 * 24 * 60 * 60 * 1000)); //equivalent to 1 month
var expires = "expires=" + d.toUTCString();
document.cookie = "cookie_name[" + variable + "]" + "=" + value + ";" + expires + ';path=/';
}
【讨论】: