How to pass an array to JS script in PHP

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.