将PHP数组值传递给JavaScript变量


Pass PHP array values to JavaScript variable

我试图在JavaScript变量中获得PHP数组的值。下面是我的代码:

    $qry="select * from optin";
    $rlt1=mysql_query($qry);
    $em_ary=array();
    while($row= mysql_fetch_array($rlt1)){
        $em_ary=$row;
        echo $em_ary['timer'];}// this echo show all records that I have in data base and I want to get all the values in Javascript

<script>
    var tmr=[];
    tmr='<?php echo json_encode($em_ary['timer']); ?>';
    alert(tmr);// this alert only shows the last record in the database 
<?script>

我哪里出错了,或者有其他方法来完成这个?提前感谢!

您需要更新这一行:

$em_ary = $row;

并将其改为:

$em_ary[] = $row;

每次要添加新元素时,都要覆盖数组。

然后,在JS部分,更新这一行:

tmr = '<?php echo json_encode($em_ary['timer']); ?>';

:

tmr = JSON.parse('<?php echo json_encode($em_ary); ?>');

希望这对你有帮助!干杯!

您正在覆盖您的$em_ary数组中的值,以便创建一个值数组,您需要将[]放在$em_ary之后,这将生成一个数组

$em_ary[]=$row;

你需要从

更新这个
tmr='<?php echo json_encode($em_ary['timer']); ?>';

tmr="<?php echo json_encode({$em_ary['timer']}); ?>";