小编典典

将PHP数组传递给JavaScript函数

javascript

我正在尝试将PHP数组变量转换为JavaScript变量。

这是我的代码:

<html>
    <head>
        <script type="text/javascript">
              function drawChart(row,day,week,month,date)
              {
                  // Some code...
              }
        </script>
    </head>

    <body>
        <?php
            for($counter = 0; $counter<count($au); $counter++)
            {
                switch($au[$counter]->id)
                {
                    case pageID.'/insights/page_active_users/day':
                        $day[] = $au[$counter]->value;
                    break;
                    case pageID.'/insights/page_active_users/week':
                        $week[] = $au[$counter]->value;
                    break;
                    case pageID.'/insights/page_active_users/month':
                        $month[] = $au[$counter]->value;
                    break;
                }
            }
        ?>
        <script>
            drawChart(600/50, '<?php echo $day; ?>', '<?php echo $week; ?>', '<?php echo $month; ?>', '<?php echo createDatesArray(cal_days_in_month(CAL_GREGORIAN, date('m',strtotime('-1 day')), date('Y',strtotime('-1 day')))); ?>');
        </script>
    </body>
</html>

我无法获得PHP数组的价值。

我该如何解决这个问题?


阅读 261

收藏
2020-04-25

共1个答案

小编典典

在下面的示例中,您具有一个PHP数组,然后首先通过一个PHP数组创建一个JavaScript数组:

<script type="javascript">
    day = new Array(<?php echo implode(',', $day); ?>);
    week = new Array(<?php echo implode(',',$week); ?>);
    month = new Array(<?php echo implode(',',$month); ?>);

    <!--  Then pass it to the JavaScript function:   -->

    drawChart(<?php echo count($day); ?>, day, week, month);
</script>
2020-04-25