简体   繁体   English

使用json_encode方法将PHP数组传递到外部Javascript函数中,结果为“未定义”

[英]Passing PHP array using json_encode method into external Javascript function gives result as 'undefined'

I have searched for that, i got some ideas from following site also. 我已经进行了搜索,也从以下站点获得了一些想法。 Passing PHP array into external Javascript function as array My sample code is below: 将PHP数组作为数组传递给外部Javascript函数我的示例代码如下:

 <?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>

For above code, I am getting undefined as alert message . 对于上述代码,我undefinedalert message Any Help would be appreciated. 任何帮助,将不胜感激。

When you use json_encode() , double-quotes are preserved in the result. 使用json_encode() ,结果中会保留双引号。 So, json_encode($array_sample) produces: 因此, json_encode($array_sample)产生:

["c1","c2"]

When this is put into your HTML, you have: 将其放入HTML中后,您将:

<INPUT type="button" value="Php Array" onclick="Test(["c1","c2"])" />

If you can tell, the double-quotes from your json-output break the HTML which break what's passed to the Test() method. 如果可以告诉您,则json-output中的双引号会破坏HTML,这会破坏传递给Test()方法的内容。

To fix this, you could use htmlentities() to convert the double-quotes to HTML-values &quot; 要解决此问题,您可以使用htmlentities()将双引号转换为HTML值&quot; :

<INPUT type="button" value="Php Array" onclick="Test(<?php echo htmlentities($newArray) ?>)" />

EDIT ( htmlentities() vs. addslashes() ) 编辑htmlentities() addslashes()
It appears that using addslashes() actually won't work because an escaped double-quote in an attribute, such as onclick="Test(\\"value\\")" is invalid. 看来使用addslashes()实际上是行不通的,因为属性中的转义双引号无效,例如onclick="Test(\\"value\\")" However, an html-entity version such as onclick="Test(&quot;value&quot;)" works. 但是,诸如onclick="Test(&quot;value&quot;)"类的html实体版本有效。

Because of this, I have changed my original answer from "use addslashes() " to "use htmlentities() "). 因此,我将原来的答案从“ use addslashes() ”更改为“ use htmlentities() ”)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM