Reputation: 145
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>
Upvotes: 1
Views: 1092
Reputation: 1282
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>
Upvotes: 4