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

How to pass array to js script using php

小云云
小云云Original
2017-11-14 10:58:088567browse

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:

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 <<
//在javascript中新建一个对象json_js,输出的代码为var json_js = ["1","2","3"];
var json_js = $helloJson;
//看看效果
//弹出窗口显示1
alert(json_js[0]);

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:

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!

Statement:
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