我有一个 Javascript 项目,我从 API 源接收 Covid-19 数据。用户输入他们希望查看数据的国家/地区(从 2020 年 3 月至今),然后使用 chart.js 将数据绘制到屏幕上。我在用户输入国家/地区的输入字段中添加了一个事件侦听器,并以这种方式检索数据。但是,当我调用我的函数来绘制数据( graphIt() )时,该函数会发生一秒钟然后消失。我理解为什么会发生这种情况,因为该函数只被调用一次,所以它很快就完成了。但是,我要如何让 chart.js 保持多久?我将把我的代码的重要部分放在这里!
索引.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