将PHP数组作为数组传递给外部Javascript函数 [英] Passing PHP array into external Javascript function as array

查看:76
本文介绍了将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)) ?>)"



<请注意PHP代码周围缺少引号('),这样就可以将数组文字传递给 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.

这篇关于将PHP数组作为数组传递给外部Javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆