简体   繁体   中英

How to pass a php array of string values to a javascript variable

I need to use php arrays in my javascript code. The arrays are defined in PHP in the same file as the javascript.

I have tried the following two ways:

var array_name = new Array('<?php echo implode("','", $php_array);?>');

and

var array_name = <?php echo json_encode($php_array);?>;

This works great if my php arrays are integers. However, when I try to do either when the array is a list of strings, then it does not work.

Any suggestions on what other options I have?

Any help appreciated.

put that json string into quotes (single quotes!)

var array_name = '<?php echo json_encode($php_array);?>';

enjooy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM