Home > Web Front-end > JS Tutorial > How to assign value to js array in php_javascript skills

How to assign value to js array in php_javascript skills

WBOY
Release: 2016-05-16 16:56:20
Original
1231 people have browsed it

Due to the requirements of the interface party, the data is processed in js, so the php program needs to retrieve the values ​​​​from the database and assign them to the js array. I haven't found a good way yet, because the data encoding of PHP arrays is different from the encoding format of JS arrays and cannot be output directly.

After searching online, I found the solution:

The PHP function library provides functions for encoding/decoding JSON: json_encode() and json_decode(), which can easily pass arrays or objects to JavaScript. Note: The JSON extension is only bound to PHP 5.2 and above.

Write the following in php:

Copy the code The code is as follows:

$arr = array('1',array('2','3'),array('new','old'));
$new_arr = json_encode($arr);//new_arr The output result is;["1",["2","3"],["new","old"]]
echo "var data =". $new_arr;

After referencing the above php file in the page, the data can be directly operated in js.
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template