As a PHP programmer, we all know that there is an irreducible relationship between PHP and JavaScript, so let's now introduce a way to pass a PHP array or object to JavaScript. With the JSON extension in PHP, you can pass an array or object to a JavaScript script, get a JSON-formatted string of arrays or objects, and write a JSON-formatted string into JavaScript code.
First, the PHP array to JS method:
code example:
<script type= "Text/javascript" > var slist = ' <?php echo urlencode (Json_encode ($data [' arr ']);? > '; var list = eval (decodeuricomponent (slist)); Drawgpsmap (list);</script>
Second, the PHP array or object is passed to the JS interactive transfer value Json_encode
Passing a PHP array or object to JavaScript can be cumbersome if the array is converted into a string of JavaScript code.
PHP 5.2 Binds the JSON extension, which makes it easier to pass an array or object to JavaScript.
JSON is a string format, and a JSON-formatted string can be assigned directly to JavaScript as an array or an object.
1. Gets the JSON-formatted string for the array or object.
code example:
Suppose you want to pass an array of $hello = Array (' 1 ', ' 2 ', ' 3 '); $helloJson = Json_encode ($hello);
2. Write the JSON-formatted string into the JavaScript code.
code example:
echo <<<eot<script language= "JavaScript" type= "Text/javascript" >//Create a new object Json_js in JavaScript, The output code is var json_js = ["1", "2", "3"];var json_js = $helloJson;//See Effect//pop-up Display 1alert (Json_js[0]);</script>eot;
The method is the same if you want to pass an object.
The above is the method of passing PHP arrays or objects to JavaScript, hoping to help everyone.