图表js PHP和JSON不会diplsay

时间:2015-10-01 15:41:48

标签: javascript php jquery json chart.js

我正在尝试通过PHP获取JSON。这是成功的,因为控制台显示json对象。 但这些值不会显示在图表上。

我翻译JSON的方式有问题吗?

// Getting PHP - JSON file
$.get('chartBar.php', {type: "bar"}, function(dataBar){
    console.log(dataBar);

//Translate JSON
    var chartjsDataBar = [];
    for (var i = 0; i < dataBar.length; i++) {
    chartjsDataBar.push(dataBar[i].data); 
    };

    var BarChartData = {
        labels : labelTags,
        datasets: [
        {        
        label: "Net Comp",
        fillColor : "#F02626",
        strokeColor : "#F02626",
        pointColor : "#F02626",
        pointStrokeColor : "#fff",
        pointHighlightFill : "#fff",
        pointHighlightStroke : "#F02626",
        data : chartjsDataBar[0]},
        {
        label: "AnalyzerHR",
        fillColor : "#26F041",
        strokeColor : "#26F041",
        pointColor : "#26F041",
        pointStrokeColor : "#fff",
        pointHighlightFill : "#fff",
        pointHighlightStroke : "#26F041",
        data : chartjsDataBar[1]},
        {
        label: "Question Right",
        fillColor : "#20AEFA",
        strokeColor : "#20AEFA",
        pointColor : "#20AEFA",
        pointStrokeColor : "#fff",
        pointHighlightFill : "#fff",
        pointHighlightStroke : "#20AEFA",
        data : chartjsDataBar[2]}

    ]};

如果我直接添加数据data : dataBar,它会显示,但当然结果都是一行混合。

PHP:

    <?php

    $array = [
        [  
    "label"=> "Net Comp",
    "color"=> "#F02626",
    "data"=> [0, 6, 7, 8, 9, 3]
], [
    "label"=> "AnalyzerHR",
    "color"=> "#26F041",
    "data"=> [ 0, 4, 3, 5, 7,  2 ]
], [
    "label"=> "Question Right",
    "color"=> "#20AEFA",
    "data"=> [ 0, 3, 1,  3,  3, 1] 
]
    ];

    if($_GET['type'] == "bar"){
        echo json_encode($array);   
    }
?>

提前谢谢

1 个答案:

答案 0 :(得分:1)

您需要将$.get设置为接收json,以便它知道将返回的数据类型。

$.get('chartBar.php', {type: "bar"}, function(dataBar){},'json');