且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将php数组作为变量传递给javascript加载url,然后返回php数组?

更新时间:2023-02-25 15:01:06

您的代码无效.如果有

$arr = array('a', 'b', 'c');
echo $arr;

您实际上得到了

Array

作为输出.不是数组的内容.要将数组从PHP输出"到JS,您必须将其转换为本地Javascript,这是json_encode出现的地方:

as the output. Not the contents of the array. To "output" an array from PHP to JS, you have to convert it to native Javascript, which is where json_encode comes in:

<?php
$arr = array('a', 'b', 'c');
?>
var js_array = <?php echo json_encode($arr) ?>;

会产生

var js_array = ["a","b","c"];

作为一般规则,每当您使用PHP生成JavaScript代码并用PHP值填充Javascript变量时,都应使用json_encode来确保生成有效的Javascript.一旦客户端开始尝试执行它,任何语法错误和整个Javascript代码块都将淹没在水中.

As a general rule, anytime you are using PHP to generate javascript code and are filling in Javascript variables with PHP values, you should use json_encode to ensure that you're generating valid Javascript. Any syntax errors and the whole Javascript code block is dead in the water once the client starts trying to execute it.