Table of Contents
1. Convert the array to JSON format
2. Get JSON data on the front end
3. Directly output JSON data in PHP
4. Use inline scripts to pass data
5. Use hidden input tags to pass data
Home Backend Development PHP Problem How to pass array to js in php

How to pass array to js in php

Apr 25, 2023 am 09:04 AM

In web development, we often need to pass data from the back end (such as PHP) to the front end (such as JavaScript). Using AJAX technology, we can obtain back-end data asynchronously without refreshing the web page. However, in some cases, we want to directly pass the back-end array to the front-end to facilitate front-end processing. This article explains how to pass arrays to JavaScript in PHP.

1. Convert the array to JSON format

Before passing the array to JavaScript, we need to convert the array into a data structure that can be recognized in JavaScript. Here we can use JSON (JavaScript Object Notation) format, which is a text format for data exchange and a syntax for representing objects in JavaScript. PHP has a built-in json_encode() function that can convert PHP arrays into JSON format.

Sample code:

$data = array('name' => 'John', 'age' => 30, 'city' => 'New York');
$data_json = json_encode($data);
echo $data_json;
Copy after login

Output result:

{"name":"John","age":30,"city":"New York"}
Copy after login

2. Get JSON data on the front end

On the front end, we can get it through AJAX request to PHP Output JSON data, sample code:

$.ajax({
    type: "POST",  // 或者 GET
    url: "data.php",  // 后端程序地址
    dataType: "json",  // 返回的数据类型
    success: function(data) {  // 成功回调函数
        console.log(data.name);
        console.log(data.age);
        console.log(data.city);
    }
});
Copy after login

It should be noted that the dataType parameter specifies the data type returned by the request, here it is set to json. Therefore, if the returned JSON format is not legal, the data will not be parsed normally.

3. Directly output JSON data in PHP

In addition to converting arrays to JSON format and then outputting them in PHP, we can also directly output arrays in JSON format. This method is more concise, but requires adding the corresponding response header at the beginning of the PHP file.

Sample code:

$data = array('name' => 'John', 'age' => 30, 'city' => 'New York');
header('Content-Type: application/json');  // 响应头,指定返回的数据类型为 JSON
echo json_encode($data);
Copy after login

On the front end, you can directly call PHP files through AJAX without parsing.

4. Use inline scripts to pass data

In PHP files, we can also use inline scripts to pass data to JavaScript. This method is relatively simple, but difficult to maintain and is not recommended.

Sample code:

$data = array('name' => 'John', 'age' => 30, 'city' => 'New York');
echo '<script> var data = ' . json_encode($data) . '; </script>';
Copy after login

After the above code converts the array into JSON format, embed it directly into the script tag, and then use the variable data to access the array on the front end.

5. Use hidden input tags to pass data

If you need to submit the array in PHP when the form is submitted, we can put the array into a hidden input tag, and then When the form is submitted, it is also passed to the backend.

Sample code:

$data = array('name' => 'John', 'age' => 30, 'city' => 'New York');
echo '<form action="process.php" method="post">';
foreach ($data as $key => $value) {
    echo '<input type="hidden" name="data[&#39; . $key . &#39;]" value="&#39; . $value . &#39;">';
}
echo '<button type="submit">提交</button>';
echo '</form>';
Copy after login

Add an array parameter named data to the form, and then add each element in the PHP array to the hidden input tag one by one through a loop. . The entire array can be obtained via $_POST['data'] on the backend.

The above are several methods on how to pass arrays to JavaScript in PHP. Different methods can be used in different scenarios, and they need to be selected according to specific needs in actual applications.

The above is the detailed content of How to pass array to js in php. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24