简体   繁体   中英

passing a php array to javascript

I have a php that echos html. Inside one of these echos I have a button that calls a javascript function. Inside of this call I pass a php variable. However when I see what the value of one of the elements is inside of the javascript I get undefined.

Any ideas?

Javascript

function addrow(innerid, teams){


    alert(teams[1]);}

Here is how I pass it, this is all inside of an echo

<input type = "button" id = '.$buttonid.'  value = "Agregar" onclick = "addrow(\'' . $leaguesarray[$numofleagues] . '\','.$teamsarray.')

So I call addrow(with a league value, and I also pass the array teamsarray from php

I've decided to try something else but I'm not getting it to work correctly.

Any suggestions?

echo '<script language="javascript">';


for ($size = 0; $size < sizeof($teamsarray);$size++){

    echo "var teamsarray[".$size."] = ".$teamsarray[$size].";\n";


    }

echo 'function addrow(innerid, size){


for (var i = 0;i< size; i++ ){

html = html + "<option value = " + teamsarray[i] + ">"+teamsarray[i]+"</option>";


    }

html = html +"</select>";
}</script>';

basically what I'm trying to do is echo the javascript through php. I'm trying to make a dropdown with values that I get from php. Which will be added dynamically with the addrow function.

It sounds like you might be looking for json_encode, so you might do something like this:

if (empty($teamsarray)) $teamsarray = array();
echo '<input type = "button" id = '.$buttonid.'  value = "Agregar" onclick = "addrow(\'' . $leaguesarray[$numofleagues] . '\','.json_encode($teamsarray).'); return false;" />';

In javascript, arrays look like: [2,4,6]. The php implode command can help here.

    $buttonid = 42;
    $leaguesarray[$numofleagues] = 66;
    $teamsarray = array(2,4,6);

    $teams = implode(',',$teamsarray);

    $input = <<<EOT
<input type="button" id="$buttonid" value="Agregar" onclick="addrow($leaguesarray[$numofleagues],[$teams])" />
EOT;
    echo $input . "\n";

Yields:

<input type="button" id="42" value="Agregar" onclick="addrow(66,[2,4,6])" />

Which I think is what you want.

EDITED:

@Dustin Grahams suggestion to use json_encode is a good one. Replace the implode with:

$teams = json_encode($teamsarray);

And drop the extra brackets from the template.

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