JavaScript saves array to cookie code _javascript tips

Source: Internet
Author: User
Tags base64 eval setcookie tojson
In JavaScript, arrays are not stored directly as cookies (PHP can), and that is to dump the array into a string, and then save it in a cookie, and we can use either ToString () or join directly on the simple one-dimensional array:
The ToString function method in JavaScript is a string representation of the returned object.
How to use: objectname.tostring ([radix])
Where objectname is a required option. The object to be represented by the string.
Radix is optional. Specifies the system in which numeric values are converted to strings.
Join is one of the methods.
Format: Objarray.join (seperator)
Purpose: Converts an array to a string, using the character specified by Seperator as a delimiter, and the same as ToString () when Seperator is a comma.
If we have a multidimensional array, we're going to use JSON.
JSON (JavaScript Object notation) is a lightweight data interchange format. Easy for people to read and write. It is also easy to machine parse and generate. It is based on JavaScript programming Language, Standard ECMA-262 a subset of 3rd Edition-december 1999. JSON uses a completely language-independent text format, but it also uses a family of C-language (c, C + +, C #, Java, JavaScript, Perl, Python, and so on). These features make JSON an ideal data exchange language.
Here we use PHP2JS function library to implement, need Json_decode and json_encode These two functions, understand PHP friend can understand the meaning of these two functions. Json_decode is json to array, Json_encode is array to JSON.
Note that JavaScript save cookies will filter some characters, such as: "{" is filtered to "{_" and so on. So filter these characters when you get cookies, or json_decode will go wrong.
The following simple examples are as follows:
Copy Code code 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.
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-\u206f\ufeff\ufff0-\uffff] /g;
var J;
var text = Str_json;
Parsing happens in four stages. In the 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). Slice (-4);
});
}
In the second stage, we run the text against regular expressions
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 being 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. 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 into that "remaining characters are only whitespace or" "
', ' or ': ' or ' {' or '} '. If So, then the "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 a
JavaScript structure. The ' {' operator is subject to a syntactic ambiguity
In Javascript:it can begin a blocks 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.
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-\u0604\u070f\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 (a) {
var c = Meta[a];
return typeof c = = ' string '? C:
' \\u ' + (' 0000 ' + a.charcodeat (0). toString). 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 are included here
The remote chance 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 this case.
if (!value) {
return ' null ';
}
Make a array to hold the partial results of stringifying this object value.
Gap + + indent;
partial = [];
Is the value of an array?
if (Object.prototype.toString.apply (value) = = ' [Object Array] ') {
The value is a 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 we value under the key of ".
Return the result of stringifying the value.
Return str (', {
': Value
});
}
Savecookie ();
Readcookie ();
</script>

Also note that the Chinese problem, may be garbled, it is suggested that multibyte characters and Chinese, such as base64 encoding decoding:
Copy Code code 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:tyler 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 to 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:tyler 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 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) |) + String.fromCharCode ((C1 & 63) | 128);
} else {
ENC = String.fromCharCode (C1 >>) (224) + String.fromCharCode (((C1 >> 6) &) | 128) + STRING.FROMCHA Rcode ((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 &) << 6) | (C2 & 63));
i + 2;
} else {
C2 = Str_data.charcodeat (i+1);
C3 = Str_data.charcodeat (i+2);
Tmp_arr[ac++] = String.fromCharCode ((c1 &) << 12) | ((C2 &) << 6) | (C3 & 63));
i + 3;
}
}
Return Tmp_arr.join (");
}
</script>

Base64_decode relies on Utf8_decode, Base64_encode relies on Utf8_encode.

Php2jsis an open source project that implements some of PHP's functions into 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.