开发者问题收集

Chart js PHP 和 JSON 不会显示

2015-10-01
89

我尝试通过 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个回答

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

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

camelCase
2015-10-01