As PHP programmers, we all know that there is an inseparable relationship between PHP and JavaScript, so now we will introduce to you the method of passing PHP arrays or objects to JavaScript. Using the json extension in php, you can pass an array or object to a javascript script, obtain a json-formatted string of the array or object, and write the json-formatted string into the javascript code.
1. How to pass arrays from php to js:
Code example:
<script type="text/javascript"> var slist = '<?php echo urlencode(json_encode($data['arr']));?>'; var list = eval(decodeURIComponent(slist)); drawGpsMap(list); </script>
2. Pass php arrays or objects to js interactively pass values json_encode
Pass PHP arrays or objects to JavaScript. It is more troublesome to convert the array into a string of JavaScript code for operation.
php 5.2 is bound with the json extension, which makes it easier to pass arrays or objects to javascript.
Json is a string format. Strings that conform to the json format can be directly assigned to JavaScript as an array or object.
1. Obtain the json format string of the array or object.
Code example:
//假设要传递的是一个数组 $hello = array('1','2','3'); $helloJson = json_encode($hello);
2. Write the json format string into the javascript code.
Code example:
echo <<<eot <script language="JavaScript" type="text/JavaScript"> //在javascript中新建一个对象json_js,输出的代码为var json_js = ["1","2","3"]; var json_js = $helloJson; //看看效果 //弹出窗口显示1 alert(json_js[0]); </script> eot;
If you want to pass an object, the method is the same.
The above is the method of passing php array or object to javascript. I hope it can help everyone.
Related recommendations:
The most complete introduction to PHP array
Several ways to define PHP arrays
The above is the detailed content of How to pass array to js script using php. For more information, please follow other related articles on the PHP Chinese website!