Home  >  Article  >  Backend Development  >  How to pass array to JS using PHP and process the data

How to pass array to JS using PHP and process the data

PHPz
PHPzOriginal
2023-04-18 14:10:32547browse

When developing web applications recently, data transfer between PHP and JS is often involved, especially the transfer of complex data structures such as arrays. This article mainly introduces how to use PHP to pass arrays to JS and use these data in JS.

1. Convert PHP array to JSON format

In PHP, we can directly use arrays to store data. But in JS, arrays are usually represented in JSON (JavaScript Object Notation) format. JSON is a lightweight data exchange format that is easy to understand and process. So before passing the PHP array to JS, we need to convert the array to JSON format.

PHP provides a built-in function json_encode() that can convert PHP arrays into JSON format. The sample code is as follows:

 '张三',
    'age' => 25,
    'interests' => array('篮球', '游泳', '音乐')
);
$json = json_encode($array);
echo $json;
?>

In the above code, we define an associative array $array, convert it to JSON format, and use the echo statement to output the JSON to the screen. The output results are as follows:

{"name":"张三","age":25,"interests":["篮球","游泳","音乐"]}

2. Parse JSON data in JS

In JS, we can use the built-in JSON object to parse JSON data. There are two main methods in JSON objects: parse() and stringify(). Among them, the parse() method is used to parse JSON strings and convert them into JS objects or arrays; and the stringify() method is used to convert JS objects or arrays into JSON strings.

The following is a sample code that uses the JSON.parse() method to parse the JSON data output in the previous section:

var json = '{"name":"张三","age":25,"interests":["篮球","游泳","音乐"]}';
var obj = JSON.parse(json);
console.log(obj.name);          //输出:张三
console.log(obj.age);           //输出:25
console.log(obj.interests[0]);  //输出:篮球

In the above code, we define a JSON string json , and parse it into a JS object obj using the JSON.parse() method. Then, we can get the data in the array by accessing the properties of obj.

It should be noted that if the JSON string format is incorrect, the parse() method will throw an exception.

3. Pass JSON data to JS

Now, we already know how to convert the array to JSON format in PHP and parse the JSON data in JS. Next, let's take a look at how to pass JSON data to JS.

There are two common ways to pass JSON data to JS: directly using the JSON string as a JS variable, or using AJAX technology to get the JSON data from the server.

  1. Using JSON strings as JS variables

This method is suitable for situations where we already have a JSON string. We can use JSON strings directly as JS variables.

The following is a sample code that uses a JSON string as a JS variable:

 '张三',
    'age' => 25,
    'interests' => array('篮球', '游泳', '音乐')
);
$json = json_encode($array);
?>

In the above code, we generated a JSON string in the PHP code and passed it to A JavaScript variable json. Then we use the JSON.parse() method to parse the json string and get the data in the array by accessing the properties of obj.

It should be noted that if the JSON string contains special characters, such as single quotes, double quotes, etc., it may cause JS code errors. To avoid this, we need to use escape characters in the JSON string.

  1. Use AJAX to obtain JSON data

If JSON data needs to be obtained dynamically from the server, we can use AJAX (Asynchronous JavaScript and XML) technology. AJAX can send a request to the server and obtain data without refreshing the page, and then display the data on the page.

The following is a sample code that uses AJAX to obtain JSON data:

 '张三',
    'age' => 25,
    'interests' => array('篮球', '游泳', '音乐')
);
$json = json_encode($array);
?>

In the above code, we create an AJAX request using the XMLHttpRequest object. Then, we open the request connection by calling the open() method, set the request method to GET, and set the requested URL to get_json.php. Next, we set up the onreadystatechange event handling function to process the returned data when the AJAX request status changes. Finally, we sent the AJAX request by calling the send() method.

It should be noted that when using AJAX requests, we need to ensure that the requested URL is correct and that the server can correctly parse the request parameters and return data in JSON format.

4. Summary

In web application development, we often need to pass complex data structures (such as arrays) from PHP to JS. To achieve this goal, we can convert the PHP array to JSON format and then parse the JSON data in JS. Here we introduce two methods of passing JSON data: using JSON strings directly as JS variables, or using AJAX technology to obtain JSON data from the server. In actual development, we should choose the appropriate method according to the specific situation in order to achieve efficient data transmission.

The above is the detailed content of How to pass array to JS using PHP and process the data. 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