JavaScript code for saving arrays to cookies

Source: Internet
Author: User
Tags tojson

Arrays in JavaScript cannot be directly saved as cookies (PHP can). Therefore, you need to convert the arrays into strings and store them in cookies. For a simple one-dimensional array, we use toString () or join:
In JavaScript, The toString function is a string representation of the returned object.
Usage: objectname. toString ([radix])
Objectname is required. The object to be represented by a string.
Radix is optional. Specifies the hexadecimal format when the numeric value is converted to a string.
Join is one of the methods.
Format: objArray. join (seperator)
Purpose: Use the character specified by seperator as the separator to convert the array into a string. When seperator is a comma, it serves the same purpose as toString.
If the multi-dimensional array is used, we need to use JSON.
JSON (JavaScript Object Notation) is a lightweight data exchange format. Easy to read and write. It is also easy to parse and generate machines. It is based on a subset of JavaScript Programming Language, Standard ECMA-262 3rd Edition-December 1999. JSON uses a completely language-independent text format, but it also uses a habit similar to the C language family (including C, C ++, C #, Java, JavaScript, Perl, Python, and so on ). These features make JSON an ideal data exchange language.
Here we use the PHP2JS function library for implementation. We need json_decode and json_encode functions. PHP users can understand the meaning of these two functions. Json_decode is from JSON to array, and json_encode is from array to JSON.
It should be noted that some characters are filtered by saving the Cookie in JavaScript, for example, "{" is filtered. Therefore, these characters must be filtered when the Cookie is obtained. Otherwise, an error occurs in json_decode.
The following is a simple example:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
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] + '<br> ');
}
}
}
Function json_decode (str_json ){
// Decodes the JSON representation into a PHP value
//
// Version 906.1806
// Discuss at: http://phpjs.org/functions/json_decode
// + Original by: Public Domain (http://www.json.org/json2.js)
// + Reimplemented by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + Improved by: T. J. Leahy
// * Example 1: json_decode ('[\ n "e", \ n {\ n "pluribus": "unum" \ n} \ n]');
// * Returns 1: ['E', {pluribus: 'unum'}]
/*
Http://www.JSON.org/json2.js
2008-11-19
Public Domain.
No warranty expressed or implied. use at your own risk.
See http://www.JSON.org/js.html
*/
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-\ signature \ 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 character characters
// Incorrectly, either silently deleting them, or treating them as line endings.
Cx. lastIndex = 0;
If (cx. test (text )){
Text = text. replace (cx, function (){
Return '\ U' +
('100' + 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
// Replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// Replace all simple value tokens with '] 'characters. Third, we delete all
// Open brackets that follow a colon or comma or that begin the text. Finally,
// We look to see that the remaining characters are only whitespace or ']' or
// ',' Or ':' or '{' or '}'. If that is so, then the text is safe for eval.
If (/^ [\], :{}\ s] * $ /.
Test (text. replace (/\\(? : ["\\\/Bfnrt] | u [0-9a-fA-F] {4})/g ,'@').
Replace (/"[^" \ n \ r] * "| true | false | null | -? \ D + (? : \. \ D *)? (? : [EE] [+ \-]? \ D + )? /G, ']').
Replace (/(? : ^ |: | ,)(? : \ S * \ [) +/g ,''))){
// In the third stage we use the eval function to compile the text into
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// In JavaScript: it can begin a block or an object literal. We wrap the text
// In parens to eliminate the ambiguity.
J = eval ('+ text + ')');
Return j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
Throw new SyntaxError ('json _ decode ');
}
Function json_encode (mixed_val ){
// Returns the JSON representation of a value
//
// Version 906.1806
// Discuss at: http://phpjs.org/functions/json_encode
// + Original by: Public Domain (http://www.json.org/json2.js)
// + Reimplemented by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + Improved by: T. J. Leahy
// * Example 1: json_encode (['E', {pluribus: 'unum'}]);
// * Returns 1: '[\ n "e", \ n {\ n "pluribus": "unum" \ n} \ n]'
/*
Http://www.JSON.org/json2.js
2008-11-19
Public Domain.
No warranty expressed or implied. use at your own risk.
See http://www.JSON.org/js.html
*/
Var json = this. window. JSON;
If (typeof json = 'object' & typeof json. stringify = 'function '){
Return json. stringify (mixed_val );
}
Var value = mixed_val;
Var quote = function (string ){
Var escapable =/[\\\ "\ u0000-\ u001f \ u007f-\ u009f \ u00ad \ u0600-\ Users \ u17b4 \ u17b5 \ u200c-\ u200f \ u2028- \ u202f \ u2060-\ u206f \ ufeff \ ufff0-\ uffff]/g;
Var meta = {// table of character substitutions
'\ B': '\ B ',
'\ T':' \ t ',
'\ N':' \ n ',
'\ F':' \ F ',
'\ R':' \ R ',
'"':'\\"',
'\\':'\\\\'
};
Escapable. lastIndex = 0;
Return escapable. test (string )?
'"' + String. replace (escapable, function (){
Var c = meta [a];
Return typeof c = 'string '? C:
'\ U' + ('000000' + a. charCodeAt (0). toString (16). slice (-4 );
}) + '"':
'"' + String + '"';
};
Var str = function (key, holder ){
Var gap = '';
Var indent = '';
Var I = 0; // The loop counter.
Var k = ''; // The member key.
Var v = ''; // The member value.
Var length = 0;
Var mind = gap;
Var partial = [];
Var value = holder [key];
// If the value has a toJSON method, call it to obtain a replacement value.
If (value & typeof value === 'object '&&
Typeof value. toJSON = 'function '){
Value = value. toJSON (key );
}
// What happens next depends on the value's type.
Switch (typeof value ){
Case 'string ':
Return quote (value );
Case 'number ':
// JSON numbers must be finite. Encode non-finite numbers as null.
Return isFinite (value )? String (value): 'null ';
Case 'boolean ':
Case 'null ':
// If the value is a boolean or null, convert it to a string. Note:
// Typeof null does not produce 'null'. The case is encoded here in
// The remote chance that this gets fixed someday.
Return String (value );
Case 'object ':
// If the type is 'object', we might be dealing with an object or an array or
// Null.
// Due to a specification blunder in ECMAScript, typeof null is 'object ',
// So watch out for that case.
If (! Value ){
Return 'null ';
}
// Make an array to hold the partial results of stringifying this object value.
Gap + = indent;
Partial = [];
// Is the value an array?
If (Object. prototype. toString. apply (value) = '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// For non-JSON values.
Length = value. length;
For (I = 0; I <length; I + = 1 ){
Partial [I] = str (I, value) | 'null ';
}
// Join all of the elements together, separated with commas, and wrap them in
// Brackets.
V = partial. length = 0? '[]':
Gap? '[\ N' + gap +
Partial. join (', \ n' + gap) +' \ n' +
Mind + ']':
'[' + Partial. join (',') + ']';
Gap = mind;
Return v;
}
// Iterate through all of the keys in the object.
For (k in value ){
If (Object. hasOwnProperty. call (value, k )){
V = str (k, value );
If (v ){
Partial. push (quote (k) + (gap? ':') + V );
}
}
}
// Join all of the member texts together, separated with commas,
// And wrap them in braces.
V = partial. length = 0? '{}':
Gap? '{\ N' + gap + partial. join (', \ n' + gap) + '\ n' +
Mind + '}': '{' + partial. join (',') + '}';
Gap = mind;
Return v;
}
};
// Make a fake root object containing our value under the key ''.
// Return the result of stringifying the value.
Return str ('',{
'': Value
});
}
Savecookie ();
Readcookie ();
</Script>

Note that Chinese characters may be garbled. We recommend that you use base64 to encode and decode multi-byte characters and Chinese characters:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function base64_decode (data ){
// Decodes string using MIME base64 algorithm
//
// Version 905.3122
// Discuss at: http://phpjs.org/functions/base64_decode
// + Original by: Taylor Akins (http://rumkin.com)
// + Improved by: Thunder. m
// + Input by: Aman Gupta
// + Improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + Bugfixed by: Onno Marsman
// + Bugfixed by: Pellentesque Malesuada
// + Improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + Input by: Brett Zamir (http://brett-zamir.me)
// + Bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
//-Depends on: utf8_decode
// * Example 1: base64_decode ('s2v2aw4gdmfuifpvbm5ldmvsza = ');
// * Returns 1: 'kevin van Zonneveld'
// Mozilla has this native
//-But breaks in 2.0.0.12!
// If (typeof this. window ['btoa'] = 'function '){
// Return btoa (data );
//}
Var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 +/= ";
Var o1, o2, o3, h1, h2, h3, h4, bits, I = 0, ac = 0, dec = "", tmp_arr = [];
If (! Data ){
Return data;
}
Data + = '';
Do {// unpack four hexets into three octets using index points in b64
H1 = b64.indexOf (data. charAt (I ++ ));
H2 = b64.indexOf (data. charAt (I ++ ));
H3 = b64.indexOf (data. charAt (I ++ ));
H4 = b64.indexOf (data. charAt (I ++ ));
Bits = h1 <18 | h2 <12 | h3 <6 | h4;
O1 = bits> 16 & 0xff;
O2 = bits> 8 & 0xff;
O3 = bits & 0xff;
If (h3 = 64 ){
Tmp_arr [ac ++] = String. fromCharCode (o1 );
} Else if (h4 = 64 ){
Tmp_arr [ac ++] = String. fromCharCode (o1, o2 );
} Else {
Tmp_arr [ac ++] = String. fromCharCode (o1, o2, o3 );
}
} While (I <data. length );
Dec = tmp_arr.join ('');
Dec = this. utf8_decode (dec );
Return dec;
}
Function base64_encode (data ){
// Encodes string using MIME base64 algorithm
//
// Version 905.2617
// Discuss at: http://phpjs.org/functions/base64_encode
// + Original by: Taylor Akins (http://rumkin.com)
// + Improved by: Bayron Guevara
// + Improved by: Thunder. m
// + Improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + Bugfixed by: Pellentesque Malesuada
// + Improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
//-Depends on: utf8_encode
// * Example 1: base64_encode ('kevin van Zonneveld ');
// * Returns 1: 's2v2aw4gdmfuifpvbm5ldmvsza ='
// Mozilla has this native
//-But breaks in 2.0.0.12!
// If (typeof this. window ['atob'] = 'function '){
// Return atob (data );
//}
Var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 +/= ";
Var o1, o2, o3, h1, h2, h3, h4, bits, I = 0, ac = 0, enc = "", tmp_arr = [];
If (! Data ){
Return data;
}
Data = this. utf8_encode (data + '');
Do {// pack three octets into four hexets
O1 = data. charCodeAt (I ++ );
O2 = data. charCodeAt (I ++ );
O3 = data. charCodeAt (I ++ );
Bits = o1 <16 | o2 <8 | o3;
H1 = bits> 18 & 0x3f;
H2 = bits> 12 & 0x3f;
H3 = bits> 6 & 0x3f;
H4 = bits & 0x3f;
// Use hexets to index into b64, and append result to encoded string
Tmp_arr [ac ++] = b64.charAt (h1) + b64.charAt (h2) + b64.charAt (h3) + b64.charAt (h4 );
} While (I <data. length );
Enc = tmp_arr.join ('');
Switch (data. length % 3 ){
Case 1:
Enc = enc. slice (0,-2) + '= ';
Break;
Case 2:
Enc = enc. slice (0,-1) + '= ';
Break;
}
Return enc;
}
Function utf8_encode (argString ){
// Encodes an ISO-8859-1 string to UTF-8
//
// Version 905.1217
// Discuss at: http://phpjs.org/functions/utf8_encode
// + Original by: Webtoolkit.info (http://www.webtoolkit.info /)
// + Improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + Improved by: sowberry
// + Tweaked by: Jack
// + Bugfixed by: Onno Marsman
// + Improved by: Yves Sucaet
// + Bugfixed by: Onno Marsman
// * Example 1: utf8_encode ('kevin van Zonneveld ');
// * Returns 1: 'kevin van Zonneveld'
Var string = (argString + ''). replace (/\ r \ n/g," \ n "). replace (/\ r/g," \ n ");
Var utftext = "";
Var start, end;
Var stringl = 0;
Start = end = 0;
Stringl = string. length;
For (var n = 0; n <stringl; n ++ ){
Var c1 = string. charCodeAt (n );
Var enc = null;
If (c1 <128 ){
End ++;
} Else if (c1> 127) & (c1 <2048 )){
Enc = String. fromCharCode (c1> 6) | 192) + String. fromCharCode (c1 & 63) | 128 );
} Else {
Enc = String. fromCharCode (c1> 12) | 224) + String. fromCharCode (c1> 6) & 63) | 128) + String. fromCharCode (c1 & 63) | 128 );
}
If (enc! = Null ){
If (end> start ){
Utftext + = string. substring (start, end );
}
Utftext + = enc;
Start = end = n + 1;
}
}
If (end> start ){
Utftext + = string. substring (start, string. length );
}
Return utftext;
}
Function utf8_decode (str_data ){
// Converts a UTF-8 encoded string to ISO-8859-1
//
// Version 905.3122
// Discuss at: http://phpjs.org/functions/utf8_decode
// + Original by: Webtoolkit.info (http://www.webtoolkit.info /)
// + Input by: Aman Gupta
// + Improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + Improved by: Norman "zEh" Fuchs
// + Bugfixed by: hitwork
// + Bugfixed by: Onno Marsman
// + Input by: Brett Zamir (http://brett-zamir.me)
// + Bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * Example 1: utf8_decode ('kevin van Zonneveld ');
// * Returns 1: 'kevin van Zonneveld'
Var tmp_arr = [], I = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;
Str_data + = '';
While (I <str_data.length ){
C1 = str_data.charCodeAt (I );
If (c1 <128 ){
Tmp_arr [ac ++] = String. fromCharCode (c1 );
I ++;
} Else if (c1> 191) & (c1 <224 )){
C2 = str_data.charCodeAt (I + 1 );
Tmp_arr [ac ++] = String. fromCharCode (c1 & 31) <6) | (c2 & 63 ));
I + = 2;
} Else {
C2 = str_data.charCodeAt (I + 1 );
C3 = str_data.charCodeAt (I + 2 );
Tmp_arr [ac ++] = String. fromCharCode (c1 & 15) <12) | (c2 & 63) <6) | (c3 & 63 ));
I + = 3;
}
}
Return tmp_arr.join ('');
}
</Script>

Base64_decode depends on utf8_decode, and base64_encode depends on utf8_encode.

PHP2JS is an open-source project that implements some PHP functions to JavaScript.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.