简体   繁体   English

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

[英]A pie chart in chart.js with data from json

I'm drawing a pie chart using data from a database.我正在使用数据库中的数据绘制饼图。 My database is very simple, but it has a different structure than all examples which I was checking.我的数据库非常简单,但它的结构与我检查的所有示例不同。 So it looks like this:所以它看起来像这样:

id | food | tickets
1  | 300  | 50 

I guess the id column is unnecessary because it won't be more records.我猜 id 列是不必要的,因为它不会有更多记录。

data.php数据.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);
?>

When I'm checking results by localhost://data.php I have this: [{"food":"300","tickets":"50"}]当我通过 localhost://data.php 检查结果时,我有这个: [{"food":"300","tickets":"50"}]

And now the problematic part:现在有问题的部分:

app.php 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);
    }
});

And of course html:当然还有 html:

index.html索引.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>

First of all you have a second definition of variable data in your Ajax success function.首先,您在 Ajax 成功 function 中有第二个变量data定义。 Function arguments (parameters) work as local variables inside functions, that is the same way as they were defined with the keyword let inside the function. Function arguments(参数)在函数内部作为局部变量工作,这与在 function 中使用关键字let定义它们的方式相同。

Second, data in dataset s require to be a number[] and your values that you get in JSON are strings.其次, dataset s 中的data需要是一个number[] ,并且您在 JSON 中获得的值是字符串。

Third, one thing is unclear to me, since describing your data set you wrote that:第三,我不清楚一件事,因为在描述您的数据集时您写道:

I guess the id column is unnecessary because it won't be more records.我猜 id 列是不必要的,因为它不会有更多记录。

but then you process the data inside of the Ajax success function as it was a multi element array of objects, ie using a for loop.但是随后您处理 Ajax 成功 function 内部的data ,因为它是对象的多元素数组,即使用for循环。 So it depends on you want to achieve with what type of data.所以这取决于你想用什么类型的数据来实现。 A trivial solution with a single row from your SQL table the Ajax success function would look like: SQL 表中的单行的简单解决方案 Ajax 成功 function 如下所示:

success: function(data) {
  console.log(data);

  var ctx1 = $("#chartcanvas-1");
  
  var chartData = {
    labels : ["food", "tickets"],
    datasets : [{
      label : "Result",
      data : [Number(data[0].food), Number(data[0].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 : chartData,
    options : options
  });
}

With multiple rows taken from your SQL table you could use each array object (ie your SQL row including the id field used as a label ) as a separate dataset. With multiple rows taken from your SQL table you could use each array object (ie your SQL row including the id field used as a label ) as a separate dataset. Since the datasets is a JSON array of objects you could transform your initial data as follows:由于数据集是 JSON 对象数组,您可以按如下方式转换初始data

function plot(data) {
  console.log(data);

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

  var datasets = data.map(row => {
    let sets = {
      label: row.id,
      data: [Number(row.food), Number(row.tickets)],
      backgroundColor: [
        "#DEB887",
        "#A9A9A9"
      ],
      borderColor: [
        "#CDA776",
        "#989898"
      ],
      borderWidth: [1, 1]
    };
    return sets;
  });
  console.log(datasets);
  
  var chartData = {
    labels : ["food", "tickets"],
    datasets : datasets
  };
  
  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 : chartData,
    options : options
  });
  
}

Finally: Emily, if you received and read this, please contact me on Skype...最后:Emily,如果您收到并阅读了此内容,请通过 Skype 与我联系...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM