[英]Passing PHP array into external Javascript function as array
I'm doing something which I need to pass an array from my php to a function on an external javascript. 我正在做一些我需要将数组从我的PHP传递到外部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">
and the javascript function is this one: 和javascript函数是这个:
function show_error_message(test) {
alert(test)
}
my $array_sample contains data which is array("1","2","3");
我的$ array_sample包含
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. 但返回警报将是Array,每当我将
$array_sample
更改为$array_sample[0]
时,我传递参数时得到的数据是1作为警报。 I wonder how can I pass the whole array on this to be fetched also by an array in javascript. 我想知道如何通过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.
好吧你可以看到,我打算将它作为错误处理的弹出消息,这就是为什么我需要它是动态的。
Use json_encode
使用
json_encode
onclick='show_error_message(<?php echo json_encode($array_sample) ?>)'
or 要么
onclick="show_error_message(<?php echo htmlspecialchars(json_encode($array_sample)) ?>)"
Notice the lack of quotes( '
) around the php code, this way an array literal is passed to show_error_message
and not a string. 注意PHP代码周围缺少引号(
'
),这样一个数组文字传递给show_error_message
而不是字符串。
Encode PHP array to json data using json_encode()
function. 使用
json_encode()
函数将PHP数组编码为json数据。
And in Javascript use JSON.parse()
to parse the Json string. 在Javascript中使用
JSON.parse()
来解析Json字符串。
The below code shows how to pass php array to javascript: 下面的代码显示了如何将php数组传递给javascript:
<script type="text/javascript">
function mufunc(a)
{
var temp = new Array();
temp = a.split('~');
for(i=0;i<temp.length;i++)
{
alert(temp[i]);
}
}
</script>
<?php
$a = array('a','b','c');
$b = implode("~",$a);
?>
<a href="javascript:void(0)" onClick="mufunc('<?php echo $b; ?>')">Click Here</a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.