[数组,cookies]JavaScript 保存数组到Cookie的代码
JavaScript中数组是无法直接保存为Cookie的(PHP可以),那要将数组转存为字符串,再保存在Cookie中,简单的一维数组我们直接用toString()或者join就可以了:JavaScript中toString函数方法是返回对象的字符串表示。
使用方法:objectname.toString([radix])
其中objectname是必选项。要得到字符串表示的对象。
radix是可选项。指定将数字值转换为字符串时的进制。
join是其中一个方法。
格式:objArray.join(seperator)
用途:以seperator指定的字符作为分隔符,将数组转换为字符串,当seperator为逗号时,其作用和toString()相同。
如果多维数组,我们就要用JSON了。
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。
这里我们使用PHP2JS的函数库来实现,需要 json_decode 和 json_encode这两个函数,懂PHP的朋友可以理解这两个函数的意思。json_decode 是JSON到数组,json_encode 是数组到JSON。
需要注意的是JavaScript 保存 Cookie 会将一些字符过滤,如:"{" 被过滤为 "{_" 等。所以在获取 Cookie 时要过滤这些字符,不然 json_decode 会出错。
下面简单举例如下:
代码如下:
function setCookie(name, value){
document.cookie = name + "="+ value;
}
function getCookie(name){
var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
if(arr != null) return unescape(arr[2]); return '';
}
function savecookie(){
var dc = {};
dc['a'] = {};
dc['a']['x'] = 'ax';
dc['a']['y'] = 'ay';
dc['a']['z'] = 'az';
dc['b'] = {};
dc['b']['x'] = 'bx';
dc['b']['y'] = 'by';
dc['b']['z'] = 'bz';
var cdc = json_encode(dc);
setCookie('testcookie', cdc);
}
function clearcookie(){
setCookie('testcookie', '');
}
function readcookie(){
var cdc = getCookie('testcookie');
cdc = cdc.replace(/,_/g, ',');
cdc = cdc.replace(/{_/g, '{');
cdc = cdc.replace(/_}/g, '}');
var dc = json_decode(cdc);
for(i in dc){
for(j in dc[i]){
document.write(i +':'+ j +':'+ dc[i][j] +'
');
}
}
}
function json_decode(str_json) {
// Decodes the JSON representation into a PHP value
//
// version: 906.1806
// discuss at:
// + original by: Public Domain ()
// + reimplemented by: Kevin van Zonneveld ()
// + improved by: T.J. Leahy
// * example 1: json_decode('[\n "e",\n {\n "pluribus": "unum"\n}\n]');
// * returns 1: ['e', {pluribus: 'unum'}]
/*
2008-11-19
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See
*/
var json = this.window.JSON;
if (typeof json === 'object' && typeof json.parse === 'function') {
return json.parse(str_json);
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
var j;
var text = str_json;
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
(责任编辑:admin)