如何将php变量传递给javascript数组?

时间:2015-07-16 10:00:58

标签: javascript php

php代码是:

GLI A/T---January---1
GLI A/T---February---1
XLI M/T---February---1
GLI A/T---March---2
GLI M/T---March---2
Grande---March---1
XLI M/T---March---2
GLI A/T---April---2
GLI M/T---April---6
XLI M/T---April---3
GLI A/T---May---1
GLI M/T---May---4
Grande---May---1
GLI A/T---July---1

我得到了以下所需的结果,它显示了每个变种每月售罄的次数。

str.format

现在问题是我想将此数据转移到javascript

2 个答案:

答案 0 :(得分:3)

如果您希望将结果作为JS数组,则可以执行以下操作:

<?php
    $sql="...";
    /* Don't forget to execute the $sql query here */
    while($row = mysqli_fetch_array($result)) {
        $myData[] = $row["Variant"]."---".$row["mname"]."---".$row["tsold"];     
    }
?>

<script>
    var myData = <?php echo json_encode($myData); ?>;
    alert( JSON.stringify(myData) );
</script>

答案 1 :(得分:2)

PHP代码:

$sql="SELECT `Variant`, COUNT(`Variant`) AS tsold,
      MONTHNAME(sold_date) AS mname
      FROM `vehicle_sold`
      GROUP BY MONTH(`sold_date`), `Variant` ";
$data = array();
while($row = mysqli_fetch_array($result)) {
    $data[] = $row;    
}

在JavaScript中:

<script>
var data = <?php echo json_encode($data); ?>;
//your JavaScript code with data
</script>