简体   繁体   中英

Passing PHP array into external Javascript function as array

I'm doing something which I need to pass an array from my php to a function on an external javascript. I'm currently doing some test right now which looks like this:

<input type="text" onclick="show_error_message('<?php echo $array_sample ?>')" readonly="readonly">

and the javascript function is this one:

function show_error_message(test) {
alert(test)
}

my $array_sample contains data which is array("1","2","3"); but the return alert would be Array and whenever I change the $array_sample into $array_sample[0] when passing the parameters I got a data which is 1 as alert. I wonder how can I pass the whole array on this to be fetched also by an array in javascript. Well as you can see, I intended it to be a popup message for error handling which is why I need it to be dynamic.

Use json_encode

onclick='show_error_message(<?php echo  json_encode($array_sample) ?>)'

or

onclick="show_error_message(<?php echo htmlspecialchars(json_encode($array_sample)) ?>)"

Notice the lack of quotes( ' ) around the php code, this way an array literal is passed to show_error_message and not a string.

Encode PHP array to json data using json_encode() function.

And in Javascript use JSON.parse() to parse the Json string.

The below code shows how to pass php array to javascript:

<script type="text/javascript">
    function mufunc(a)
    {
        var temp = new Array();
        temp = a.split('~');
        for(i=0;i<temp.length;i++)
        {
            alert(temp[i]); 
        }
    }
</script>

<?php
    $a = array('a','b','c');
    $b = implode("~",$a);
?>
<a href="javascript:void(0)" onClick="mufunc('<?php echo $b; ?>')">Click Here</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM