2017-07-26 53 views
-1

我可以成功地將索引數組傳遞給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> 
+1

[轉換PHP關聯數組轉換爲JavaScript對象]可能的複製(https://stackoverflow.com/questions/21153805/convert-php-associative-array-into- javascript-object) –

+0

@AlexanderNied它的答案是使用json_encode(),這正是我想要做的。 –

+0

對不起,我的錯。 –

回答

1

在生成JSON的報價迷惑HTML解析器。您需要對標籤屬性的內容進行實體編碼。您可以使用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> 
+0

感謝您的建議!但警報消息顯示「未定義」。它不顯示數組的值... –

+0

奇怪 - 它對我來說非常適合。你能在瀏覽器中查看源代碼並共享嗎? – RichGoldMD

+0

哎呀...對不起....我剛剛得到一個錯字...它現在正常工作!!!! 非常感謝你!!!!!!!!! –