簡體   English   中英

如何使用json_encode()將php關聯數組作為參數傳遞給Javascript函數

[英]How to pass an php associative array as argument to Javascript function with json_encode()

我可以使用以下代碼成功將索引數組傳遞給javascript函數。 例如:

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

生成的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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM