How to pass an php associative array as argument to Javascript function with json_encode() -
i can sucessfully pass index array javascript function below code. 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 want change array associative array. however, doesn't work more...
is there problem code ?
how should fix it? thank !
my code 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 generated json confuse html parser. need entity encode contents of tag attributes. can use htmlspecialchars()
or htmlentities()
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>
Comments
Post a Comment