简体   繁体   English

如何使用json_encode()将php关联数组作为参数传递给Javascript函数

[英]How to pass an php associative array as argument to Javascript function with json_encode()

I can sucessfully pass an index array to the javascript function with below code. 我可以使用以下代码成功将索引数组传递给javascript函数。 For example: 例如:

<?php
$arr = array(1, 2, 3);
?>
<button onclick="test(<?=json_encode($arr)?>);">test</button>
<script>
function test(x){
  alert(x[0]);
  alert(x[1]);
  alert(x[2]);
}
</script>

Now I want to change the array to be an associative array. 现在,我想将数组更改为关联数组。 However, it doesn't work any more... 但是,它不再起作用了...

Is there any problem with my code ? 我的代码有问题吗?

How should I fix it? 我应该如何解决? Thank you very much ! 非常感谢你 !

My code is as below: 我的代码如下:

<?php
$arr = [ "A" => 1, "B" => 2, "C" => 3 ];
?>
<button onclick="test(<?=json_encode($arr)?>);">test</button>
<script>
function test(x){
  alert(x["A"]);
  alert(x["B"]);
  alert(x["C"]);
}
</script>

The quotes in the generated JSON confuse the html parser. 生成的JSON中的引号会使html解析器感到困惑。 You need to entity encode the contents of tag attributes. 您需要对标签属性的内容进行实体编码。 You can use htmlspecialchars() or htmlentities() for this: 您可以为此使用htmlspecialchars()htmlentities()

<?php
$arr = [ "A" => 1, "B" => 2, "C" => 3 ];
?>
<button onclick="test(<?=htmlentities(json_encode($arr))?>);">test</button>
<script>
function test(x){
  alert(x["A"]);
  alert(x["B"]);
  alert(x["C"]);
}
</script>

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

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