在条形图上显示undefine

时间:2017-06-19 08:51:52

标签: php charts

美好的一天。我遇到了这个问题,我不知道如何解决。首先,这是我的代码:

$(document).ready(function() {

$.ajax({
    url: "test.php",
    method: "GET",
    success: function(data) {
        console.log(data);
        var shclYear = [];
        var enrls = [];

        for(var i in data) {
            shclYear.push(data[i].schoolyear);
            enrls.push(data[i].enrollees);
        }

        var chartData = {
            labels: shclYear,
            datasets : [
                {
                    label : "School Year",
                    data : enrls
                }
            ]
        };

        var ctx = $('#myCanvas');

        var barGraph = new Chart(ctx, {
            type: 'bar',
            data: chartData

        });
    },
    error: function(data) {
        console.log(data);
    }
}); });

test.php以json_encode格式生成相同的数据:

[{"schoolyear":"2010","enrollees":"100"},{"schoolyear":"2011","enrollees":"150"},{"schoolyear":"2012","enrollees":"300"},{"schoolyear":"2013","enrollees":"250"}]

我想知道,我在我的HTML中,它显示未定义,未定义。有人请解释原因。非常感谢你。

顺便说一下,这里是我的PHP代码:`include(' dbFunction.php');

$dbOperation = new dbFunctions();
$qryData = $dbOperation->selectQry('Select schoolyear, enrollees From testData');

$data = array();

//for ($x=0; $row=$qryData->fetch(); $x++) {
foreach ($qryData as $row) {
    # code...
//}
    $data[] = array_unique($row);

    //echo $data .'<br>';
}

echo json_encode($data);`

1 个答案:

答案 0 :(得分:0)

[]是一个数组{},而不是一个对象for ( .. in ..)

因此,不应该使用for (var i = 0; i < data.length; i++) { shclYear.push(data[i].schoolyear); enrls.push(data[i].enrollees); }

相反,使用传统的for循环......

data.forEach(function (row) {
  shclYear.push(row.schoolyear);
  enrls.push(row.enrollees);
});

或每个......

$.ajax({
  url: "test.php",
  method: "GET",
  dataType: "json",
  ...

另外,可能想在ajax调用上将类型设置为json ...

=SUMIF(A:A, A2, B:B)