JavaScript 保存数组到 Cookie 的方法

大部分的浏览器一个网站只支持保存20个Cookie,超过20个Cookie,旧的Cookie会被最新的Cookie代替。那么如果要有超过20个 Cookie要保存只能将Cookie存为数组然后保存到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 会出错。

下面简单举例如下:
  1. <script type="text/javascript">  
  2. function setCookie(name, value){  
  3.  document.cookie = name + "="+ value;  
  4. }  
  5.   
  6. function getCookie(name){  
  7.  var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));  
  8.  if(arr != null) return unescape(arr[2]); return '';  
  9. }  
  10.   
  11. function savecookie(){  
  12.  var dc = {};  
  13.    
  14.  dc['a'] = {};  
  15.  dc['a']['x'] = 'ax';  
  16.  dc['a']['y'] = 'ay';  
  17.  dc['a']['z'] = 'az';  
  18.    
  19.  dc['b'] = {};  
  20.  dc['b']['x'] = 'bx';  
  21.  dc['b']['y'] = 'by';  
  22.  dc['b']['z'] = 'bz';  
  23.    
  24.  var cdc = json_encode(dc);  
  25.  setCookie('testcookie', cdc);  
  26. }  
  27.   
  28. function clearcookie(){  
  29.  setCookie('testcookie''');  
  30. }  
  31.   
  32. function readcookie(){  
  33.  var cdc = getCookie('testcookie');  
  34.  cdc = cdc.replace(/,_/g, ',');  
  35.  cdc = cdc.replace(/{_/g, '{');  
  36.  cdc = cdc.replace(/_}/g, '}');  
  37.   
  38.  var dc = json_decode(cdc);  
  39.  for(i in dc){  
  40.   for(j in dc[i]){  
  41.    document.write(i +':'+ j +':'+ dc[i][j] +'<br>');  
  42.   }  
  43.  }  
  44. }  
  45.   
  46. function json_decode(str_json) {  
  47.     // Decodes the JSON representation into a PHP value   
  48.     //   
  49.     // version: 906.1806   
  50.     // discuss at: http://phpjs.org/functions/json_decode   
  51.     // +      original by: Public Domain (http://www.json.org/json2.js)   
  52.     // + reimplemented by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)   
  53.     // + improved by: T.J. Leahy   
  54.     // *     example 1: json_decode('[\n    "e",\n    {\n    "pluribus": "unum"\n}\n]');   
  55.     // *     returns 1: ['e', {pluribus: 'unum'}]   
  56.     /* 
  57.         http://www.JSON.org/json2.js 
  58.         2008-11-19 
  59.         Public Domain. 
  60.         NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. 
  61.         See http://www.JSON.org/js.html 
  62.     */  
  63.   
  64.     var json = this.window.JSON;  
  65.     if (typeof json === 'object' && typeof json.parse === 'function') {  
  66.         return json.parse(str_json);  
  67.     }  
  68.   
  69.     var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;  
  70.     var j;  
  71.     var text = str_json;  
  72.   
  73.     // Parsing happens in four stages. In the first stage, we replace certain   
  74.     // Unicode characters with escape sequences. JavaScript handles many characters   
  75.     // incorrectly, either silently deleting them, or treating them as line endings.   
  76.     cx.lastIndex = 0;  
  77.     if (cx.test(text)) {  
  78.         text = text.replace(cx, function (a) {  
  79.             return '\\u' +  
  80.             ('0000' + a.charCodeAt(0).toString(16)).slice(-4);  
  81.         });  
  82.     }  
  83.   
  84.     // In the second stage, we run the text against regular expressions that look   
  85.     // for non-JSON patterns. We are especially concerned with '()' and 'new'   
  86.     // because they can cause invocation, and '=' because it can cause mutation.   
  87.     // But just to be safe, we want to reject all unexpected forms.   
  88.   
  89.     // We split the second stage into 4 regexp operations in order to work around   
  90.     // crippling inefficiencies in IE's and Safari's regexp engines. First we   
  91.     // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we   
  92.     // replace all simple value tokens with ']' characters. Third, we delete all   
  93.     // open brackets that follow a colon or comma or that begin the text. Finally,   
  94.     // we look to see that the remaining characters are only whitespace or ']' or   
  95.     // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.   
  96.     if (/^[\],:{}\s]*$/.  
  97.         test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').  
  98.             replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').  
  99.             replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {  
  100.   
  101.         // In the third stage we use the eval function to compile the text into a   
  102.         // JavaScript structure. The '{' operator is subject to a syntactic ambiguity   
  103.         // in JavaScript: it can begin a block or an object literal. We wrap the text   
  104.         // in parens to eliminate the ambiguity.   
  105.   
  106.         j = eval('(' + text + ')');  
  107.   
  108.         return j;  
  109.     }  
  110.   
  111.     // If the text is not JSON parseable, then a SyntaxError is thrown.   
  112.     throw new SyntaxError('json_decode');  
  113. }  
  114.   
  115. function json_encode(mixed_val) {  
  116.     // Returns the JSON representation of a value   
  117.     //   
  118.     // version: 906.1806   
  119.     // discuss at: http://phpjs.org/functions/json_encode   
  120.     // +      original by: Public Domain (http://www.json.org/json2.js)   
  121.     // + reimplemented by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)   
  122.     // + improved by: T.J. Leahy   
  123.     // *     example 1: json_encode(['e', {pluribus: 'unum'}]);   
  124.     // *     returns 1: '[\n    "e",\n    {\n    "pluribus": "unum"\n}\n]'   
  125.     /* 
  126.         http://www.JSON.org/json2.js 
  127.         2008-11-19 
  128.         Public Domain. 
  129.         NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. 
  130.         See http://www.JSON.org/js.html 
  131.     */  
  132.     var json = this.window.JSON;  
  133.     if (typeof json === 'object' && typeof json.stringify === 'function') {  
  134.         return json.stringify(mixed_val);  
  135.     }  
  136.   
  137.     var value = mixed_val;  
  138.   
  139.     var quote = function (string) {  
  140.         var escapable = /[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;  
  141.         var meta = {    // table of character substitutions   
  142.             '\b''\\b',  
  143.             '\t''\\t',  
  144.             '\n''\\n',  
  145.             '\f''\\f',  
  146.             '\r''\\r',  
  147.             '"' : '\\"',  
  148.             '\\': '\\\\'  
  149.         };  
  150.   
  151.         escapable.lastIndex = 0;  
  152.         return escapable.test(string) ?  
  153.         '"' + string.replace(escapable, function (a) {  
  154.             var c = meta[a];  
  155.             return typeof c === 'string' ? c :  
  156.             '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);  
  157.         }) + '"' :  
  158.         '"' + string + '"';  
  159.     };  
  160.   
  161.     var str = function(key, holder) {  
  162.         var gap = '';  
  163.         var indent = '    ';  
  164.         var i = 0;          // The loop counter.   
  165.         var k = '';          // The member key.   
  166.         var v = '';          // The member value.   
  167.         var length = 0;  
  168.         var mind = gap;  
  169.         var partial = [];  
  170.         var value = holder[key];  
  171.   
  172.         // If the value has a toJSON method, call it to obtain a replacement value.   
  173.         if (value && typeof value === 'object' &&  
  174.             typeof value.toJSON === 'function') {  
  175.             value = value.toJSON(key);  
  176.         }  
  177.   
  178.         // What happens next depends on the value's type.   
  179.         switch (typeof value) {  
  180.             case 'string':  
  181.                 return quote(value);  
  182.   
  183.             case 'number':  
  184.                 // JSON numbers must be finite. Encode non-finite numbers as null.   
  185.                 return isFinite(value) ? String(value) : 'null';  
  186.   
  187.             case 'boolean':  
  188.             case 'null':  
  189.                 // If the value is a boolean or null, convert it to a string. Note:   
  190.                 // typeof null does not produce 'null'. The case is included here in   
  191.                 // the remote chance that this gets fixed someday.   
  192.   
  193.                 return String(value);  
  194.   
  195.             case 'object':  
  196.                 // If the type is 'object', we might be dealing with an object or an array or   
  197.                 // null.   
  198.                 // Due to a specification blunder in ECMAScript, typeof null is 'object',   
  199.                 // so watch out for that case.   
  200.                 if (!value) {  
  201.                     return 'null';  
  202.                 }  
  203.   
  204.                 // Make an array to hold the partial results of stringifying this object value.   
  205.                 gap += indent;  
  206.                 partial = [];  
  207.   
  208.                 // Is the value an array?   
  209.                 if (Object.prototype.toString.apply(value) === '[object Array]') {  
  210.                     // The value is an array. Stringify every element. Use null as a placeholder   
  211.                     // for non-JSON values.   
  212.   
  213.                     length = value.length;  
  214.                     for (i = 0; i < length; i += 1) {  
  215.                         partial[i] = str(i, value) || 'null';  
  216.                     }  
  217.   
  218.                     // Join all of the elements together, separated with commas, and wrap them in   
  219.                     // brackets.   
  220.                     v = partial.length === 0 ? '[]' :  
  221.                     gap ? '[\n' + gap +  
  222.                     partial.join(',\n' + gap) + '\n' +  
  223.                     mind + ']' :  
  224.                     '[' + partial.join(',') + ']';  
  225.                     gap = mind;  
  226.                     return v;  
  227.                 }  
  228.   
  229.                 // Iterate through all of the keys in the object.   
  230.                 for (k in value) {  
  231.                     if (Object.hasOwnProperty.call(value, k)) {  
  232.                         v = str(k, value);  
  233.                         if (v) {  
  234.                             partial.push(quote(k) + (gap ? ': ' : ':') + v);  
  235.                         }  
  236.                     }  
  237.                 }  
  238.   
  239.                 // Join all of the member texts together, separated with commas,   
  240.                 // and wrap them in braces.   
  241.                 v = partial.length === 0 ? '{}' :  
  242.                 gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +  
  243.                 mind + '}' : '{' + partial.join(',') + '}';  
  244.                 gap = mind;  
  245.                 return v;  
  246.         }  
  247.     };  
  248.   
  249.     // Make a fake root object containing our value under the key of ''.   
  250.     // Return the result of stringifying the value.   
  251.     return str('', {  
  252.         '': value  
  253.     });  
  254. }  
  255.   
  256. savecookie();  
  257. readcookie();  
  258. </script>  
  259.   
  260. 还要注意的就是中文问题,可能会乱码,建议将多字节字符及中文等用 base64 编码解码:  
  261.   
  262. <script type="text/javascript">  
  263. function base64_decode( data ) {  
  264.     // Decodes string using MIME base64 algorithm   
  265.     //   
  266.     // version: 905.3122   
  267.     // discuss at: http://phpjs.org/functions/base64_decode   
  268.     // +   original by: Tyler Akins (http://rumkin.com)   
  269.     // +   improved by: Thunder.m   
  270.     // +      input by: Aman Gupta   
  271.     // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)   
  272.     // +   bugfixed by: Onno Marsman   
  273.     // +   bugfixed by: Pellentesque Malesuada   
  274.     // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)   
  275.     // +      input by: Brett Zamir (http://brett-zamir.me)   
  276.     // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)   
  277.     // -    depends on: utf8_decode   
  278.     // *     example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');   
  279.     // *     returns 1: 'Kevin van Zonneveld'   
  280.     // mozilla has this native   
  281.     // - but breaks in 2.0.0.12!   
  282.     //if (typeof this.window['btoa'] == 'function') {   
  283.     //    return btoa(data);   
  284.     //}   
  285.   
  286.     var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";  
  287.     var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = [];  
  288.   
  289.     if (!data) {  
  290.         return data;  
  291.     }  
  292.   
  293.     data += '';  
  294.   
  295.     do {  // unpack four hexets into three octets using index points in b64   
  296.         h1 = b64.indexOf(data.charAt(i++));  
  297.         h2 = b64.indexOf(data.charAt(i++));  
  298.         h3 = b64.indexOf(data.charAt(i++));  
  299.         h4 = b64.indexOf(data.charAt(i++));  
  300.   
  301.         bits = h1<<18 | h2<<12 | h3<<6 | h4;  
  302.   
  303.         o1 = bits>>16 & 0xff;  
  304.         o2 = bits>>8 & 0xff;  
  305.         o3 = bits & 0xff;  
  306.   
  307.         if (h3 == 64) {  
  308.             tmp_arr[ac++] = String.fromCharCode(o1);  
  309.         } else if (h4 == 64) {  
  310.             tmp_arr[ac++] = String.fromCharCode(o1, o2);  
  311.         } else {  
  312.             tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);  
  313.         }  
  314.     } while (i < data.length);  
  315.   
  316.     dec = tmp_arr.join('');  
  317.     dec = this.utf8_decode(dec);  
  318.   
  319.     return dec;  
  320. }  
  321.   
  322. function base64_encode( data ) {  
  323.     // Encodes string using MIME base64 algorithm   
  324.     //   
  325.     // version: 905.2617   
  326.     // discuss at: http://phpjs.org/functions/base64_encode   
  327.     // +   original by: Tyler Akins (http://rumkin.com)   
  328.     // +   improved by: Bayron Guevara   
  329.     // +   improved by: Thunder.m   
  330.     // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)   
  331.     // +   bugfixed by: Pellentesque Malesuada   
  332.     // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)   
  333.     // -    depends on: utf8_encode   
  334.     // *     example 1: base64_encode('Kevin van Zonneveld');   
  335.     // *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='   
  336.     // mozilla has this native   
  337.     // - but breaks in 2.0.0.12!   
  338.     //if (typeof this.window['atob'] == 'function') {   
  339.     //    return atob(data);   
  340.     //}   
  341.   
  342.     var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";  
  343.     var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc="", tmp_arr = [];  
  344.   
  345.     if (!data) {  
  346.         return data;  
  347.     }  
  348.   
  349.     data = this.utf8_encode(data+'');  
  350.   
  351.     do { // pack three octets into four hexets   
  352.         o1 = data.charCodeAt(i++);  
  353.         o2 = data.charCodeAt(i++);  
  354.         o3 = data.charCodeAt(i++);  
  355.   
  356.         bits = o1<<16 | o2<<8 | o3;  
  357.   
  358.         h1 = bits>>18 & 0x3f;  
  359.         h2 = bits>>12 & 0x3f;  
  360.         h3 = bits>>6 & 0x3f;  
  361.         h4 = bits & 0x3f;  
  362.   
  363.         // use hexets to index into b64, and append result to encoded string   
  364.         tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);  
  365.     } while (i < data.length);  
  366.   
  367.     enc = tmp_arr.join('');  
  368.   
  369.     switch( data.length % 3 ){  
  370.         case 1:  
  371.             enc = enc.slice(0, -2) + '==';  
  372.         break;  
  373.         case 2:  
  374.             enc = enc.slice(0, -1) + '=';  
  375.         break;  
  376.     }  
  377.   
  378.     return enc;  
  379. }  
  380.   
  381. function utf8_encode ( argString ) {  
  382.     // Encodes an ISO-8859-1 string to UTF-8   
  383.     //   
  384.     // version: 905.1217   
  385.     // discuss at: http://phpjs.org/functions/utf8_encode   
  386.     // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)   
  387.     // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)   
  388.     // +   improved by: sowberry   
  389.     // +    tweaked by: Jack   
  390.     // +   bugfixed by: Onno Marsman   
  391.     // +   improved by: Yves Sucaet   
  392.     // +   bugfixed by: Onno Marsman   
  393.     // *     example 1: utf8_encode('Kevin van Zonneveld');   
  394.     // *     returns 1: 'Kevin van Zonneveld'   
  395.     var string = (argString+'').replace(/\r\n/g, "\n").replace(/\r/g, "\n");  
  396.   
  397.     var utftext = "";  
  398.     var start, end;  
  399.     var stringl = 0;  
  400.   
  401.     start = end = 0;  
  402.     stringl = string.length;  
  403.     for (var n = 0; n < stringl; n++) {  
  404.         var c1 = string.charCodeAt(n);  
  405.         var enc = null;  
  406.   
  407.         if (c1 < 128) {  
  408.             end++;  
  409.         } else if((c1 > 127) && (c1 < 2048)) {  
  410.             enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);  
  411.         } else {  
  412.             enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);  
  413.         }  
  414.         if (enc !== null) {  
  415.             if (end > start) {  
  416.                 utftext += string.substring(start, end);  
  417.             }  
  418.             utftext += enc;  
  419.             start = end = n+1;  
  420.         }  
  421.     }  
  422.   
  423.     if (end > start) {  
  424.         utftext += string.substring(start, string.length);  
  425.     }  
  426.   
  427.     return utftext;  
  428. }  
  429.   
  430. function utf8_decode ( str_data ) {  
  431.     // Converts a UTF-8 encoded string to ISO-8859-1   
  432.     //   
  433.     // version: 905.3122   
  434.     // discuss at: http://phpjs.org/functions/utf8_decode   
  435.     // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)   
  436.     // +      input by: Aman Gupta   
  437.     // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)   
  438.     // +   improved by: Norman "zEh" Fuchs   
  439.     // +   bugfixed by: hitwork   
  440.     // +   bugfixed by: Onno Marsman   
  441.     // +      input by: Brett Zamir (http://brett-zamir.me)   
  442.     // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)   
  443.     // *     example 1: utf8_decode('Kevin van Zonneveld');   
  444.     // *     returns 1: 'Kevin van Zonneveld'   
  445.     var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;  
  446.   
  447.     str_data += '';  
  448.   
  449.     while ( i < str_data.length ) {  
  450.         c1 = str_data.charCodeAt(i);  
  451.         if (c1 < 128) {  
  452.             tmp_arr[ac++] = String.fromCharCode(c1);  
  453.             i++;  
  454.         } else if ((c1 > 191) && (c1 < 224)) {  
  455.             c2 = str_data.charCodeAt(i+1);  
  456.             tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));  
  457.             i += 2;  
  458.         } else {  
  459.             c2 = str_data.charCodeAt(i+1);  
  460.             c3 = str_data.charCodeAt(i+2);  
  461.             tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));  
  462.             i += 3;  
  463.         }  
  464.     }  
  465.   
  466.     return tmp_arr.join('');  
  467. }  
  468. </script>  
  469.   
  470. base64_decode 依赖 utf8_decode ,base64_encode 依赖 utf8_encode。  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值