0

** 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>
4

2 回答 2

1

(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>
于 2013-09-16T20:42:25.637 回答
0

如果您想避免使用 htmlspecialchars(),请将您的 onClick 用单引号括起来,然后转义 json 字符串引号。这并不能确保执行能力(如果您的 json 包含单引号,它将中断),但它可以用于此问题的目的。

试试这样:

<a href="#" onClick='shohmultiple(\'<?php echo(json_encode($array)); ?>\')'>Click Here</a>
于 2013-09-16T19:19:02.547 回答