简体   繁体   中英

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. 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. You need to entity encode the contents of tag attributes. You can use htmlspecialchars() or htmlentities() for this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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