【发布时间】:2021-11-04 12:56:59
【问题描述】:
我有一个 Javascript 项目,我从 API 源接收 Covid-19 数据。用户输入他们希望查看数据的国家/地区(从 2020 年 3 月到今天),然后使用 chart.js 将数据绘制到屏幕上。我在用户输入国家/地区的输入字段中添加了一个事件侦听器,并以这种方式检索数据。但是,当我调用我的函数来绘制数据( graphIt() )时,该函数会发生一秒钟然后消失。我理解为什么会发生这种情况,因为该函数只被调用一次,所以它可以快速执行。但是,我如何让 chart.js 保持多久?我将把我的代码的重要部分放在这里!
index.html
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.min.js"></script>
<script src="{% static 'viewCasesChart/index.js' %}"></script>
<div id="banner">
<div id="banner_details">
<h2>CoData</h2>
</div>
</div>
<div id="one_line">
<div id="main_title">
<h1>Covid-19 Data</h1>
</div>
<div id="user_query_data">
<form id="country_form">
<input type="text" placeholder="Country" id="country">
<input type="submit" value="Search">
</form>
</div>
</div>
<div id="confirmed_graph">
<canvas id="myChart" height="500" width="300"></canvas>
</div>
index.js
document.addEventListener('DOMContentLoaded', () => {
//make a global variable and put default value into it
var country = "Italy";
document.getElementById('country_form').addEventListener('submit', () => {
var delayInMilliseconds = 100000; //
country = document.getElementById('country').value;
console.log("test 1", country);
graphit();
})
async function graphit() {
document.getElementById('myChart').style.display = "block";
const dataset = await dataToGraph();
console.log("dataset.xs", dataset.xs);
console.log("dataset.ys", dataset.ys);
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'line',
data: {
labels: dataset.xs,
datasets: [{
label: `Covid 19 Confirmed cases in ${country}`,
data: dataset.ys,
backgroundColor: ['rgba(255, 99, 132, 0.2)'],
borderColor: ['rgba(255, 99, 132, 1)'],
borderWidth: 1,
fill: false,
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Confirmed Cases'
}
}],
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Date'
}
}],
}
}
});
};
async function dataToGraph() {
const xs = [];
const ys = [];
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
today = yyyy + '-' + mm + '-' + dd;
console.log("test 2", country);
fetch(`https://webhooks.mongodb-stitch.com/api/client/v2.0/app/covid-19-qppza/service/REST-API/incoming_webhook/countries_summary?country=${country}&min_date=2020-04-22&max_date=${today}`)
.then(response => response.json())
.then(days => {
days.forEach(day => {
ys.push(day.confirmed);
xs.push(day.date);
})
})
console.log("xs", xs);
console.log("ys", ys);
console.log(`https://webhooks.mongodb-stitch.com/api/client/v2.0/app/covid-19-qppza/service/REST-API/incoming_webhook/countries_summary?country=${country}&min_date=2020-04-22&max_date=${today}`);
return { xs, ys };
};
}); // Edit: final closing brackets were missing
【问题讨论】:
-
一定遗漏了一些重要的代码,因为当你制作图表时它会一直存在,除非你自己销毁它或隐藏画布
-
@JürgenFink,非常感谢你帮助我。这解决了我遇到的所有问题。你是一位伟大的老师和解释者。
-
@Nayeemur 谢谢 - 你的问题很有趣,因此你得到了我的第一个支持???? - 祝贺并欢迎堆栈溢出。注意:我刚刚编辑了我的答案,当数据在
dataToGraph(event)函数内的后台myChart.data.datasets[0].label = "loading ... ${country}"中加载时在UI 中添加反馈(例如“正在加载...德国”....)。请记住,数据正在后台异步加载,因为fetch()已经是异步的 - 因此用户知道后台正在发生某些事情。
标签: javascript fetch chart.js form-submit chart.js3