[英]Updating HTML data from JS file (HTML/JQuery)
我正在制作一个冠状病毒跟踪网站,但无法在 HTML 文件中自动更新数据。 这是我的 JS 代码:
(async()=>{
// define some globals
var update = async()=>{
// download the data
console.log('Report: Download Started');
var url = 'https://cov19.cc/report.json?v='+Math.random();
var res = await fetch(url);
var report = await res.json();
// set the last updated time
$('#last_updated').text(moment.utc(report.last_updated).fromNow());
// get variable data
var world = report.regions.world;
var total_confirmed = report.regions.world.totals.confirmed;
document.getElementById("total_confirmed").innerHTML = total_confirmed.commaSplit();
var total_critical = world.totals.critical;
document.getElementById("total_critical").innerHTML = total_critical.commaSplit();
var total_deaths = world.totals.deaths;
document.getElementById("total_deaths").innerHTML = total_deaths.commaSplit();
var total_active = world.totals.confirmed - (world.totals.deaths + world.totals.recovered);
document.getElementById("total_active").innerHTML = total_active.commaSplit();
var total_recovered = world.totals.recovered;
document.getElementById("total_recovered").innerHTML = total_recovered.commaSplit();
// hide the loading icon
$('#loader').hide();
};
// store last updated date
var old_last_updated;
// check for the last update
var update_check = async()=>{
console.log('Checking for updates');
var res = await fetch('https://cov19.cc/last_updated.txt');
var last_updated = await res.text();
// if the last updated date is newer than the stored last updated date then update the variable and update the table with the new data
if(old_last_updated == last_updated)return;
old_last_updated = last_updated;
update();
};
// initialize
update_check();
// check for updates every 60 seconds
setInterval(update_check, 60000);
})();
//cov19 prototypes
String.prototype.commaSplit = function() {
return this.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};
Number.prototype.commaSplit = String.prototype.commaSplit;
这就是我在 HTML 文件中显示数据的方式:
<p style="font-size: 60px; color: #F5F2D0;
text-align: center; font-weight: 600; margin-bottom: 0";
id="total_confirmed">
</p>
数据仅在我刷新页面时更改,我怎样才能使其自动更新而无需刷新页面? 我认为由于变量在更新 function 中,它们会自动更改。 我必须在我的 HTML 代码中调用 function 吗? 我已经坚持了很长时间,非常感谢您的帮助。 我对 JQuery 还是新手,所以这可能是一个简单的修复。 谢谢
我认为你的代码工作得很好。 您看不到任何更新,因为
if(old_last_updated == last_updated)return;
old_last_updated = last_updated;
这是决定是否要更新 DOM 的明智检查(如果数据没有更改,那么为什么要更新?)
我只是在此检查之前添加了一个时间戳,以显示 DOM 更新(没有问题),因此您的检查不会让它更新。 (我还更改了更新检查的频率,以便测试更容易:从 60 秒改为 10 秒。)
(async() => { // define some globals var update = async() => { // download the data console.log('Report: Download Started'); var url = 'https://cov19.cc/report.json?v=' + Math.random(); var res = await fetch(url); var report = await res.json(); // set the last updated time jQuery('#last_updated').text(moment.utc(report.last_updated).fromNow()); // get variable data var world = report.regions.world; var total_confirmed = report.regions.world.totals.confirmed; document.getElementById("total_confirmed").innerHTML = total_confirmed.commaSplit(); var total_critical = world.totals.critical; document.getElementById("total_critical").innerHTML = total_critical.commaSplit(); var total_deaths = world.totals.deaths; document.getElementById("total_deaths").innerHTML = total_deaths.commaSplit(); var total_active = world.totals.confirmed - (world.totals.deaths + world.totals.recovered); document.getElementById("total_active").innerHTML = total_active.commaSplit(); var total_recovered = world.totals.recovered; document.getElementById("total_recovered").innerHTML = total_recovered.commaSplit(); // hide the loading icon $('#loader').hide(); }; // store last updated date var old_last_updated; // check for the last update var update_check = async() => { console.log('Checking for updates'); var res = await fetch('https://cov19.cc/last_updated.txt'); var last_updated = await res.text(); console.log('last_updated.txt:', last_updated) // just to see that your code updates: $('#query_time').text(Date.now()); // if the last updated date is newer than the stored last updated date then update the variable and update the table with the new data if (old_last_updated == last_updated) return; old_last_updated = last_updated; update(); }; // initialize update_check(); // check for updates every 60 seconds setInterval(update_check, 10000); })(); //cov19 prototypes String.prototype.commaSplit = function() { return this.toString().replace(/\B(?=(\d{3})+(?,\d))/g, ";"); }. Number.prototype.commaSplit = String.prototype;commaSplit;
.display-class { /*font-size: 60px; color: #F5F2D0; text-align: center; font-weight: 600; margin-bottom: 0;*/ }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script> <p id="total_confirmed" class="display-class">TOTAL CONFIRMED</p> <div id="last_updated"></div> <div id="query_time"></div>
这是您的代码的一些修改版本:
(async() => { // define some globals var update = async(text, updateTime) => { // download the data console.log('Report: Download Started'); var url = 'https://cov19.cc/report.json?v=' + Math.random(); var res = await fetch(url); var report = await res.json(); // set the last updated time jQuery('#last_updated').text(moment.utc(report.last_updated).fromNow() + ` queried: ${updateTime}`); // get variable data var world = report.regions.world; var total_confirmed = report.regions.world.totals.confirmed; document.getElementById("total_confirmed").innerHTML = total_confirmed.commaSplit() + ` queried: ${updateTime}`; var total_critical = world.totals.critical; document.getElementById("total_critical").innerHTML = total_critical.commaSplit() + ` queried: ${updateTime}`; var total_deaths = world.totals.deaths; document.getElementById("total_deaths").innerHTML = total_deaths.commaSplit() + ` queried: ${updateTime}`; var total_active = world.totals.confirmed - (world.totals.deaths + world.totals.recovered); document.getElementById("total_active").innerHTML = total_active.commaSplit() + ` queried: ${updateTime}`; var total_recovered = world.totals.recovered; document.getElementById("total_recovered").innerHTML = total_recovered.commaSplit() + ` queried: ${updateTime}`; // hide the loading icon $('#loader').hide(); }; // store last updated date var old_last_updated; // check for the last update var update_check = async() => { console.log('Checking for updates'); var res = await fetch('https://cov19.cc/last_updated.txt'); var last_updated = await res.text(); console.log('last_updated.txt:', last_updated) // if the last updated date is newer than the stored last updated date then update the variable and update the table with the new data // if (old_last_updated == last_updated) return; old_last_updated = last_updated; update(last_updated, Date.now()); }; // initialize update_check(); // check for updates every 60 seconds setInterval(update_check, 10000); })(); //cov19 prototypes String.prototype.commaSplit = function() { return this.toString().replace(/\B(?=(\d{3})+(?,\d))/g, ";"); }. Number.prototype.commaSplit = String.prototype;commaSplit;
.display-class { /*font-size: 60px; color: #F5F2D0; text-align: center; font-weight: 600; margin-bottom: 0;*/ }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script> <p id="total_confirmed" class="display-class">TOTAL CONFIRMED</p> <div id="last_updated"></div> <div id="total_confirmed"></div> <div id="total_critical"></div> <div id="total_deaths"></div> <div id="total_active"></div> <div id="total_recovered"></div>
在这里,我删除了明智的更新检查并将查询时间添加到显示的所有字符串的末尾 - 您可以看到它们很好地更新(间隔 10 秒)。 没问题。
(async() => { // define some globals var update = async(text, updateTime) => { // download the data console.log('Report: Download Started'); var url = 'https://cov19.cc/report.json?v=' + Math.random(); try { var res = await fetch(url); var report = await res.json(); } catch (err) { console.log(err) } // set the last updated time document.getElementById('last_updated').innerHTML = moment.utc(report.last_updated).fromNow() + `<br />query time: ${new Date(Date.now())}<br /><br />` // adding total confirmed document.getElementById('total_confirmed').textContent = 'TOTAL CONFIRMED: ' + report.regions.world.totals.confirmed.toLocaleString('en-US') // set data list document.getElementById('data_container').innerHTML = createHTMLTemplate(report.regions.world.totals) // hide the loading icon $('#loader').hide(); }; // store last updated date var old_last_updated; // check for the last update var update_check = async() => { console.log('Checking for updates'); var res = await fetch('https://cov19.cc/last_updated.txt'); var last_updated = await res.text(); // if the last updated date is newer than the stored last updated date then update the variable and update the table with the new data // if (old_last_updated == last_updated) return; old_last_updated = last_updated; update(last_updated, Date.now()); }; // initialize update_check(); // check for updates every 10 seconds setInterval(update_check, 10000); })(); function createHTMLTemplate(data) { let html = '' for (let key in data) { html += `<div>${key}: ${data[key].toLocaleString('en-US')}</div>` } html += `<div>active: ${(data.confirmed - (data.deaths + data.recovered)).toLocaleString('en-US')}</div>` return html }
.display-class { /*font-size: 60px; color: #F5F2D0; text-align: center; font-weight: 600; margin-bottom: 0;*/ }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script> <p id="total_confirmed" class="display-class">TOTAL CONFIRMED</p> <div id="last_updated"></div> <div id="data_container"></div>
您可以通过以下方式使代码更易于维护 - 将代码提取到函数中(例如创建 HTML 模板) - 删除不必要的函数( commaSpit()
就是这样的 function - toLocaleString('en-US')
也一样(以及更多)
我在jsfiddle
上试过你的代码。
一件事 - 在您在问题中显示的p
标签中:
你放了;
在您的style
属性中的"
之后。所以改变它。
我没有做其他更改,它正在工作:
https://jsfiddle.net/17w0d2pq/
如果您仍然无法让它在您的系统上运行,请添加您在console
中遇到的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.