Home  >  Article  >  Backend Development  >  How to pass array to js in php

How to pass array to js in php

PHPz
PHPzOriginal
2023-04-20 09:10:05817browse

Data passing between PHP and JavaScript is an important topic in web development, which involves a variety of different methods, but passing arrays is still an important issue, considering that both PHP and JS have different data structures and language features, this issue can be tricky. However, using some simple and effective tricks, you can easily pass arrays between PHP and JS. In this article, I will introduce you to several techniques for passing arrays from PHP to JS, I hope it will be helpful to you.

Method 1: Use json_encode()

JSON is a lightweight data format that is widely used for data transmission between web applications. PHP provides a built-in function called json_encode(), which can serialize a PHP array into JSON format and then pass it to JS. The JSON format is very easy to parse and generate because it is plain text and does not require any specific locale. Below is a simple PHP script that uses the json_encode() method to convert an array into JSON format:

<?php
    $arr = array("apple", "banana", "orange");
    $json = json_encode($arr);
    echo $json;
?>

This will output a string similar to:

["apple","banana","orange"]

Now, you can Use JavaScript's built-in JSON parser (JSON.parse()) to parse the string into a JS array:

<script>
    var jsArray = JSON.parse('<?php echo $json; ?>');
</script>

Method 2: Use Ajax

Ajax (Asynchronous JavaScript and XML) is asynchronous JavaScript and XML technology, which allows you to send asynchronous requests to the server to obtain data without having to refresh the entire page. When using Ajax, you can export the array data processed by PHP into XML format data and pass it to JS through Ajax.

First, you need to use PHP to convert the array into an XML formatted string and then return it to the Ajax request:

<?php
    $arr = array("apple", "banana", "orange");

    $xml = new SimpleXMLElement(&#39;<root/>');
    array_walk_recursive($arr, array ($xml, 'addChild'));
    echo $xml->asXML();
?>

In JS, you need to use Ajax (XMLHttpRequest object) to Obtain data in XML format:

<script>
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var xmlDoc = this.responseXML;
            var jsArray = Array.from(xmlDoc.getElementsByTagName("root")[0].childNodes).map(function(node){return node.firstChild.nodeValue;});
        }
    };
    xhttp.open("GET", "array_to_xml.php", true);
    xhttp.send();
</script>

Method 3: Use hidden fields

This technique is to pass PHP array data to the HTML page, and then use hidden fields in JS to obtain the data. HTML form elements (for example, input elements) all have a so-called value attribute, which allows you to pass a value to the server when the form is submitted. Likewise, you can pass array data into a hidden field on the HTML page and get it via JS. Here is one way to use hidden fields:

<?php
    $arr = array("apple", "banana", "orange");
?>
<input type="hidden" id="php_array" value="<?php echo implode(",", $arr); ?>">
<script>
    var jsArr = document.getElementById("php_array").value.split(",");
</script>

In this example, the PHP code separates the values ​​​​in the array with commas and then uses it as the value of the hidden field. In JS, you can use the value attribute to extract the value and group it into an array.

Method 4: Using JavaScript variables

This method is to pass PHP array data to JavaScript code and use JavaScript variables to store the array data. PHP writes the array data as a string of JS code and then outputs it to the browser. JS can use the string to generate an array. Here is an example of using JavaScript variables:

<?php
    $arr = array("apple", "banana", "orange");
    $js_array = json_encode($arr);
?>
<script>
    var jsArr = <?php echo $js_array; ?>;
</script>

In this example, PHP uses the json_encode() method to convert the array into JSON format and then writes it as a JS code string. JS code can directly use the jsArr variable to obtain array data.

In this article, we briefly introduced how PHP passes arrays to JS. You can use a variety of techniques to pass data from PHP to JS, but one of the most popular and practical methods is using JSON JavaScript Object Notation. JSON lets you easily convert PHP arrays to JS arrays and helps you achieve seamless data transfer between PHP and JS.

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