Home > Backend Development > PHP Tutorial > How to pass array to js script using php

How to pass array to js script using php

小云云
Release: 2023-03-17 13:04:02
Original
8766 people have browsed it

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 = &#39;<?php echo urlencode(json_encode($data[&#39;arr&#39;]));?>&#39;;
  var list = eval(decodeURIComponent(slist));
  drawGpsMap(list);
</script>
Copy after login

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(&#39;1&#39;,&#39;2&#39;,&#39;3&#39;);
$helloJson = json_encode($hello);
Copy after login

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;
Copy after login

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:

Definition of php array

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!

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