我有一个从服务器获取的整数数组,我试图将信息显示为条形图。
这是我的代码:
<script type="application/javascript">
const ctx = document.getElementById("chart").getContext("2d");
const counts = [];
const dates = [];
$(document).ready(function () {
drawChart()
console.log("document ready");
$("#date_form").submit(function (ev) {
ev.preventDefault();
let url = $("#date_form").serialize();
console.log("/data/?" + url);
fetch("http://127.0.0.1:8000/data/?" + url)
.then((respone) => respone.json())
.then((data) => {
var start_date = jQuery('input[name="start_date"]').val();
var end_date = jQuery('input[name="end_date"]').val();
let last_date = new Date(Date.parse(end_date));
let first_date = new Date(Date.parse(start_date));
let current_date = new Date();
current_date = new Date(first_date.getTime()- first_date.getTimezoneOffset() * 60000);
<!--populates dates-->
while(current_date.getDate() <= last_date.getDate()){
current_date = new Date(current_date.getTime() - current_date.getTimezoneOffset() * 60000);
dates.push(current_date.toISOString().substr(0,10))
counts.push(0)
current_date.setDate(current_date.getDate()+1)
}
data.forEach(function (object, index) {
if (dates.includes(object.pk)) {
let index = (element) => element = object.pk
counts[dates.indexOf(object.pk)] = object.fields.count
}
});
console.log(dates)
console.log(counts)
console.log("going to draw")
drawChart();
});
});
});
function drawChart() {
new Chart(ctx, {
type: 'bar',
data: {
labels: dates,
datasets: [{
data: counts,
backgroundColor: "#7eff41"
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
// Global Options
Chart.defaults.global.defaultFontFamily = "Lato";
Chart.defaults.global.defaultFontSize = 15;
Chart.defaults.global.defaultFontColor = "#ff0058";
dates.length = 0;
counts.length = 0;
}
</script>
将其传递到ChartJS的数据字段后,将得到以下内容。
让我抓狂的是事实,如果我手动传递数据(即[23,45,53,65],它就可以正常工作。
尝试将折线图与获取的数据一起使用,并且效果很好,这意味着它不是异步问题。