Chart.Js Donut无法正确计算JSON数据

时间:2017-07-26 17:20:20

标签: javascript jquery chart.js

使用静态数据时,圆环图表显示完美,例如:

$.ajax({
        url: 'includes/stats.php?show',
        dataType: 'json',
        success: function (response) 
        {
            console.log(response['CARS']); //I see 2
            console.log(response['MOTORS']); //I see 0
            console.log(response['BOATS']); //I see 0
            var autoData = [
                {
                    value: 2,
                    color: "#4286f4",
                    highlight: "#4d6fa5",
                    label: "Cars"
                },
                {
                    value: 0,
                    color: "#3fe276",
                    highlight: "#51a36d",
                    label: "Motor Homes"
                },
                {
                    value: 0,
                    color: "#bde234",
                    highlight: "#87964e",
                    label: "Boats"
                }
            ];
            var ctx = document.getElementById("onChart").getContext("2d");
            var myNewChart = new Chart(ctx).Doughnut(autoData);                 
        }
});

我正在进行JSON调用,但是在回调中,我正在使用静态数据[2,0,0]填充autoData变量,这样图表出现并为“Cars”计算100%,因为它是只有一些价值(2),其他是0 ... 当我这样做时:

$.ajax({
        url: 'includes/stats.php?show',
        dataType: 'json',
        success: function (response) 
        {
            console.log(response['CARS']); //I see 2
            console.log(response['MOTORS']); //I see 0
            console.log(response['BOATS']); //I see 0
            var autoData = [
                {
                    value: response['CARS'],
                    color: "#4286f4",
                    highlight: "#4d6fa5",
                    label: "Cars"
                },
                {
                    value: response['MOTORS'],
                    color: "#3fe276",
                    highlight: "#51a36d",
                    label: "Motor Homes"
                },
                {
                    value: response['BOATS'],
                    color: "#bde234",
                    highlight: "#87964e",
                    label: "Boats"
                }
            ];
            var ctx = document.getElementById("onChart").getContext("2d");
            var myNewChart = new Chart(ctx).Doughnut(autoData);                 
        }
});

我得到的图表看起来像填充图表的2%切片......这里发生了什么?

1 个答案:

答案 0 :(得分:0)

我正在用PHP构建JSON,如:

    $data = $autoQuery->fetch_array();
    $autoData = array('CARS' => $data['CARS'],
                    'MOTORS' => $data['MOTORS'],
                    'BOATS' => $data['BOATS']);
    echo json_encode($autoData);

这不起作用。当我在每个$ data变量之前放入intval()时,它有效!