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 MATLAB怎么通过柱坐标变换画开口是圆形的旋转抛物面?
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿