将PHP数组作为数组传递给外部Javascript函数
我正在做一些我需要将数组从我的php传递到外部javascript上的函数的东西。我现在正在进行一些测试,看起来像这样:
I'm doing something which I need to pass an array from my php to a function on an external javascript. I'm currently doing some test right now which looks like this:
<input type="text" onclick="show_error_message('<?php echo $array_sample ?>')" readonly="readonly">
并且javascript函数是这一个:
and the javascript function is this one:
function show_error_message(test) {
alert(test)
}
我的$ array_sample包含的数据是数组(1,2,3);
但返回警报将是数组和每当我将 $ array_sample
更改为 $ array_sample [0]
时,传递参数我得到的数据是1作为警报。我想知道如何通过javascript中的数组传递整个数组。好吧你可以看到,我打算将它作为一个弹出消息来处理错误,这就是为什么我需要它是动态的。
my $array_sample contains data which is array("1","2","3");
but the return alert would be Array and whenever I change the $array_sample
into $array_sample[0]
when passing the parameters I got a data which is 1 as alert. I wonder how can I pass the whole array on this to be fetched also by an array in javascript. Well as you can see, I intended it to be a popup message for error handling which is why I need it to be dynamic.
使用 json_encode
onclick='show_error_message(<?php echo json_encode($array_sample) ?>)'
或
onclick="show_error_message(<?php echo htmlspecialchars(json_encode($array_sample)) ?>)"
'),这样就可以将数组文字传递给 show_error_message
而不是一个字符串。
Notice the lack of quotes('
) around the php code, this way an array literal is passed to show_error_message
and not a string.