将 JavaScript 数组传递给 PHP 数组

问题描述

我是新手。我想在 PHP 中创建文本文件,因为我需要 Clint 端的两个数组。问题是我已将数组从 JavaScript 传递给 PHP,但在 PHP 中它确实转换为 JavaScript 数组的单个字符串。

test.html

<form method="post" id="theform" action="example.PHP">
    <!-- your existing form fields -->

    <input type="hidden" id="markers" name="markers">

    <button>Submit</button>
</form>

<script>
    window.onload = function () {
        var form = document.getElementById('theform');
        form.addEventListener('submit',function () {
            var markersField = document.getElementById('markers');
            var markers = [1,2,3];
            markersField.value = JSON.stringify(markers);
        });
    }
</script>

example.PHP

<?PHP 
    $array=json_decode($_POST['markers']);
    foreach($array as $value){
        print $value;
    }
?>

example.PHP输出

123

预期产出

$array[0] = 1;
$array[1] = 2;
$array[2] = 3;

解决方法

您的代码的预期输出确实是 123,因为您实际上并未打印数组 $array,而是打印了数组的单个值。要显示数组,您需要使用 print_r()var_dump() 并在浏览器中查看源代码或使用 HTML (<pre><?php print_r($array);?></pre>)更漂亮的印刷品。

此外,要确保 json_decode() 不会创建对象而是数组,请确保启用参数 $assoc。解决办法是:

PHP 8

<?php 
$array = json_decode($_POST['markers'],assoc: true);

print('<pre>');
print_r($array);
print('</pre>');

PHP 7 或更低

<?php 
$array = json_decode($_POST['markers'],true);

print('<pre>');
print_r($array);
print('</pre>');