我可以成功地將索引數組傳遞給javascript函數與下面的代碼。例如:如何通過php關聯數組作爲參數與JavaScript函數與json_encode()
<?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>
現在我想將數組更改爲關聯數組。但是,它不再工作...
我的代碼有問題嗎?
我該如何解決?非常感謝你 !
我的代碼如下:
<?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>
[轉換PHP關聯數組轉換爲JavaScript對象]可能的複製(https://stackoverflow.com/questions/21153805/convert-php-associative-array-into- javascript-object) –
@AlexanderNied它的答案是使用json_encode(),這正是我想要做的。 –
對不起,我的錯。 –