如何在javascript中打印php数组

时间:2016-05-14 12:35:58

标签: javascript php json

我有一个数组$results,我需要在我的代码的javascript部分中使用它。我尝试了json_encode()但它没有用..

这是代码

<?php
    //...
    include realpath($_SERVER['DOCUMENT_ROOT'] . '/Classes/Controllers/ReportController.php');
    $vaccRep= ReportController::getVacRep();

    include realpath($_SERVER['DOCUMENT_ROOT'] . '/Classes/Controllers/VaccineController.php');
    $names=VaccineController::getVCName();
?>

<canvas id="bar" height="195" width="250" style="width: 250px; height: 195px;"></canvas>
<script>
    //THIS IS THE PART THAT WILL BE THE OTPUT OF THE QUERY

    var barChartData = {
        labels: <?php$obj=json_encode($names); var_dump($obj);?>,
        datasets: [{
            highlightFill: "#45668e",
            highlightStroke: "#45668e",
            fillColor : "#1ABC9C",
            strokeColor : "#1ABC9C",
            data: <?php $obj=json_encode($vaccRep); var_dump($obj);?>
        }]
    };


    new Chart(document.getElementById("bar").getContext("2d")).Bar(barChartData);
    <?php $obj=json_encode($vaccRep); var_dump($obj);?>
</script>

4 个答案:

答案 0 :(得分:0)

怎么样

<?php
    echo "<script>";
    echo "var $results = JSON.parse('" . json_encode($results) . "');";
    echo "<script>";
?>

然后在任何地方的javascript代码中使用$ results,但请确保在使用之前加载此脚本块。

答案 1 :(得分:0)

您可以尝试这样在javascript中打印php数组

<?php
  $abc=["a","b","c"];
?>
<script type="text/javascript">
  var abc = "<?php echo (implode(',',$abc));?>";
  var abcArr = abc.split(",");
  console.log(abcArr);
</script>

答案 2 :(得分:0)

您只需使用此代码:

<?php
    $array = ["a", 1, 2, "b,"];
    echo "<script>";
    echo "var data = ".json_encode($array).';';
    echo "</script>";
?>

此代码的输出将是: <script>var data = ["a",1,2,"b,"];</script>,什么会创建正确的javascript数组。

答案 3 :(得分:0)

简单地使用json_encode()在js中回显php数组,如下所示:

$phpArray = array('name'=>'mani','email'=>'test@gmail.com','mobile'=>'123467890');

PHP数组看起来像这样

Array
(
    [name] => mani
    [email] => test@gmail.com
    [mobile] => 123467890
)

<script>
var jsArray = [];
var jsArray = <?php echo json_encode($phpArray);?>;
console.log(jsArray);
</script>

您将在控制台中获得此功能

 Object { name="mani",  email="test@gmail.com",  mobile="123467890"}