如何修复Uncaught TypeError:无法读取属性' 0'未定义的

时间:2017-05-24 13:18:06

标签: javascript php

我想将我的数据从mssql通过php发送到我的图表。为此,我使用$.get函数从mssql接收数据。 但我收到错误:Uncaught TypeError: Cannot read property '0' of undefined显然我无法访问对象。

我的PHP代码:

if(isset($_GET['employeesChart'])) {
    getemployeesChart($conn);
}

function getemployeesChart($conn) {
  $sql ="SELECT * FROM employee;
  $result = sqlsrv_query($conn, $sql);
  $row = sqlsrv_fetch_array($result);
  $isAtWork = $row['Work'];
  $isAtHome = $row['Home'];
  $data = array('isAtWork' => $isAtWork, 'isAtHome' => $isAtHome);
  echo json_encode($data)
}

和我的javascript代码:

var data = {
    labels: [
        "Home",
        "Work",
        "Break"
    ],
    datasets: [{
        data: [],
        backgroundColor: ["#FF6384","#36A2EB","#FFCE56"],
        hoverBackgroundColor: ["#FF6384","#36A2EB","#FFCE56"]
    }]
};

$.get("employees.inc.php?employeesChart", function(data){
    var result = $.parseJSON(data);
    var test = data.datasets[0].data.push(result[0],result[1]);
    myDoughnutChart.update();
});

// Doughnut Chart
var myDoughnutChart = new Chart(ctx, {
    type: 'doughnut',
    data: data,
    options: {
            responsive: true,
            legend: {
                position: 'right',
            },
            animation: {
                animateScale: true,
                animateRotate: true
            }
        }
});

我不明白为什么我会收到错误。当我使用console.log(result)测试它时获得两个整数,但代码示例使data.datasets[0].data.push(result[0],result[1])出错

0 个答案:

没有答案