[英]How to implement dynamic data on chartjs?
I need your help to learn how to dynamically implement data from a json file to Chartjs. 我需要您的帮助,以学习如何动态地将数据从json文件实现到Chartjs。 The fields that I need to fill dynamically are
labels
and data
. 我需要动态填充的字段是
labels
和data
。
JSON File <<<
[
{
"EFICAZ_TAB_ITEM_ID":1,
"EFICAZ_PERCENTS":99
},
{
"EFICAZ_TAB_ITEM_ID":2,
"EFICAZ_PERCENTS":99
},
{
"EFICAZ_TAB_ITEM_ID":3,
"EFICAZ_PERCENTS":99
}
]
CHARTJS <<<
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: [???],
datasets: [{
label: "My First dataset",
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [???],
}]
},
// Configuration options go here
options: {}
});
I have used $.ajax()
to fetch JSON data, and save the data in two arrays, then you can use these arrays for your chart label and data. 我使用
$.ajax()
来获取JSON数据,并将数据保存在两个数组中,然后可以将这些数组用于图表标签和数据。 Hope this helps! 希望这可以帮助!
var lbl = [];
var dta = [];
$.ajax({
url: "test.json",
dataType: 'json',
async: false,
success: function(data) {
$.each(data, function(i, field){
lbl.push(field.EFICAZ_TAB_ITEM_ID
);
dta.push(field.EFICAZ_PERCENTS);
});
}
});
$.getJSON("test.json", function(result){
$.each(result, function(i, field){
lbl.push(field.EFICAZ_TAB_ITEM_ID
);
dta.push(field.EFICAZ_PERCENTS);
});
});
var ctx = document.getElementById("myCanvas").getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: lbl,
datasets: [{
label: "My First dataset",
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: dta,
}]
},
// Configuration options go here
options: {}
});
Here is example 这是例子
document.addEventListener('DOMContentLoaded', function(){ var chartData = [ { "EFICAZ_TAB_ITEM_ID":1, "EFICAZ_PERCENTS":21 }, { "EFICAZ_TAB_ITEM_ID":2, "EFICAZ_PERCENTS":55 }, { "EFICAZ_TAB_ITEM_ID":3, "EFICAZ_PERCENTS":32 } ] var labels = []; var values = []; chartData.forEach(function(el,key){ labels.push(el.EFICAZ_TAB_ITEM_ID); values.push(el.EFICAZ_PERCENTS); }) var ctx = document.getElementById('myChart').getContext('2d'); var chart = new Chart(ctx, { // The type of chart we want to create type: 'line', // The data for our dataset data: { labels: labels, datasets: [{ label: "My First dataset", backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgb(255, 99, 132)', data: values, }] }, // Configuration options go here options: {} }); })
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script> <canvas id="myChart" width="400" height="200"></canvas>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.