Home >Web Front-end >JS Tutorial >JavaScript code to save array to cookie_javascript skills

JavaScript code to save array to cookie_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:29:361171browse

Arrays in JavaScript cannot be directly saved as cookies (PHP can). Then the array must be transferred to a string and then saved in a cookie. For a simple one-dimensional array, we can directly use toString() or join:
The toString function method in JavaScript returns the string representation of the object.
Usage: objectname.toString([radix])
Where objectname is a required option. To get the object represented by a string.
radix is ​​optional. Specifies the base when converting numeric values ​​to strings.
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, its function is the same as toString().
If it is a multi-dimensional array, we have to use JSON.
JSON (JavaScript Object Notation) is a lightweight data exchange format. Easy for humans to read and write. It is also easy for machines to parse and generate. 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 also uses conventions similar to the C language family (including C, C, C#, Java, JavaScript, Perl, Python, etc.). These properties make JSON an ideal data exchange language.
Here we use the PHP2JS function library to implement it, which requires the two functions json_decode and json_encode. Friends who know PHP can understand the meaning of these two functions. json_decode is JSON to array, json_encode is array to JSON.
It should be noted that JavaScript will filter some characters when saving cookies, such as: "{" is filtered into "{_", etc. Therefore, these characters must be filtered when obtaining cookies, otherwise json_decode will cause an error.
The following is a simple example:

Copy the code The code is as follows:



还要注意的就是中文问题,可能会乱码,建议将多字节字符及中文等用 base64 编码解码:
复制代码 代码如下:



base64_decode 依赖 utf8_decode ,base64_encode 依赖 utf8_encode。

PHP2JS是开源项目,是将PHP的部分函数实现到JavaScript。
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn