doujiao0110 2013-09-16 19:05
浏览 265
已采纳

使用json_encode通过onClick()将字符串数组传递给javascript

** Update - While my solution works (and I haven't yet heard why not to use htmlspeciatchars()), I am including a modified version of Jacob Mouka's creative solution which successfully avoids having to use it. **

I am trying to pass an array of strings to javascript via onClick() using json_encode. Just passing json_encode($array) did not work. I surmised that since json_encode($array) returns ["a","b","c"], the quotes were the issue. I was successful with wrapping the json_encode($array) with htmlentities() and then using JSON.parse(array) to turn the string back into an array.

I read all the posts on this site and none showed this combination as a solution and I wonder if I am making it more complicated than it should be. Is htmlentities() the correct function to use? Is there a simpler way of sending this array from an onclick() to a javascript function? Thanks in advance.

Javascript

<script>
function shohmultiple(array){
  alert("Aray as string: " + array);
  array = JSON.parse(array)
  for (i=0; i< array.length; i++){ 
    alert(array[i]);
  }
}
</script>

<?php $array=array("a", "b", "c"); ?>

HTML

<a href="#" onClick="shohmultiple('<?php echo htmlspecialchars(json_encode($array)) ?>')">Click Here</a>

Modified Solution from Jacob Mouka (for the workflow I am seeking)

Javascript

<script type="text/javascript">

function shohmultiple (array) {
    for (i=0; i< array.length; i++){ 
        alert(array[i]);
    }
}
</script>

HTML

<?php $array = array("a", "b", "c"); ?>

<script>
    // calling this before outputting <a href> works
    <?php  echo "var js_array = " . json_encode($array) . ";"; ?>
</script>

<a href="#" onClick="shohmultiple(js_array);">Click Here</a>
  • 写回答

2条回答 默认 最新

  • dty47696 2013-09-16 20:42
    关注

    (edit after some testing)

    The problem is actually that json_encode uses double quotes, which messes with the inline javascript (it uses double quotes too). If there was some way to force json_encode to use single quotes, that would fix it (but I don't think there is). A cludgy solutions is something like:

    <script type="text/javascript">
    <?php
        $array = array("a", "b", "3");
        echo "var js_array = " . json_encode($array) . ";";
    ?>
        function shohmultiple (val) {
            window.foo = val;
            console.log('got',val);
        }
    
    </script>
    
    
    <a href="#" onClick="shohmultiple(js_array);">Click Here</a>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 网络科学导论,网络控制
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)