chart.js中的饼图,其中包含来自json的数据

时间:2017-05-01 20:39:46

标签: javascript php chart.js pie-chart

我正在使用数据库中的数据绘制饼图。 我的数据库非常简单,但它的结构与我检查的所有示例不同。所以它看起来像这样:

id | food | tickets
1  | 300  | 50 

我猜id列是不必要的,因为它不会有更多记录。

data.php

 <?php
//setting header to json
header('Content-Type: application/json');

require_once "../polaczenie.php";

//get connection
$mysqli = @new mysqli($host,$db_user,$db_password,$db_name);

if(!$mysqli){
    die("Connection failed: " . $mysqli->error);
}

//query to get data from the table
$query = sprintf("SELECT id,food, tickets FROM arch_kategorie ORDER BY id");

//execute query
$result = $mysqli->query($query);

//loop through the returned data
$data = array();
foreach ($result as $row) {
    $data[] = $row;
}

//free memory associated with result
$result->close();

//close connection
$mysqli->close();

//now print the data
print json_encode($data);
?>

当我通过localhost检查结果时://data.php我有这个: [{ “食品”: “300”, “机票”: “50”}]

现在有问题的部分:

app.php

$(document).ready(function(){
    $.ajax({
        url : "data.php",
        type : "GET",
        success : function(data){
            console.log(data);

            var food= [];
            var tickets= [];

            for(var i in data) {
                food.push(data[i].food);
                tickets.push(data[i].tickets);
            }

            var ctx1 = $("#chartcanvas-1");

            var data = {
                labels : ["food", "tickets"],
                datasets : [{
                    label : "Result",
                    data : food, tickets
                    backgroundColor : [
                        "#DEB887",
                        "#A9A9A9"
                    ],
                    borderColor : [
                        "#CDA776",
                        "#989898"
                    ],
                    borderWidth : [1, 1]
                }]
            };

            var options = {
                title : {
                    display : true,
                    position : "top",
                    text : "Pie Chart",
                    fontSize : 18,
                    fontColor : "#111"
                },
                legend : {
                    display : true,
                    position : "bottom"
                }
            };

            var chart1 = new Chart( ctx1, {
                type : "pie",
                data : data,
                options : options
            });
        });
    },
    error : function(data) {
        console.log(data);
    }
});

当然是html:

index.html

<style type="text/css">
    #chart-container {
        width: 80%;
        height: auto;
    }
</style>

<div class="chart-container">
    <div class="chart-container">
        <canvas id="chartcanvas-1"></canvas>
    </div>
</div>

0 个答案:

没有答案