我已经搜索过了,我也从以下网站得到了一些想法。 Passing PHP array into external Javascript function as array 我的示例代码如下:
<?php $array_sample = array("c1","c2"); $newArray = json_encode($array_sample); ?>
<INPUT type="button" value="Php Array" onclick="Test(<?php echo $newArray ?>)" />
<script language="javascript"> function Test(test_arr){ alert(test_arr); }</script>
对于上面的代码,我收到未定义
作为警报消息
。
任何帮助将不胜感激。
最佳答案
当您使用json_encode()
时,双引号会保留在结果中。因此,json_encode($array_sample)
产生:
["c1","c2"]
将其放入 HTML 中后,您将获得:
<INPUT type="button" value="Php Array" onclick="Test(["c1","c2"])" />
如果您能看出来,json 输出中的双引号会破坏 HTML,从而破坏传递给 Test()
方法的内容。
要解决此问题,您可以使用 htmlentities()
将双引号转换为 HTML 值 "
:
<INPUT type="button" value="Php Array" onclick="Test(<?php echo htmlentities($newArray) ?>)" />
编辑(htmlentities()
与 addslashes()
)
看来使用 addslashes()
实际上不起作用,因为属性中存在转义双引号,例如 onclick="Test(\"value\")"
是无效的。但是,诸如 onclick="Test("value")"
之类的 html 实体版本可以工作。
因此,我将原来的答案从“use addslashes()
”更改为“use htmlentities()
”)。
关于php - 使用 json_encode 方法将 PHP 数组传递到外部 Javascript 函数中,结果为 'undefined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13283319/