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 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制