首页 > 解决方案 > 从 JS 文件 (HTML/JQuery) 更新 HTML 数据

问题描述

我正在制作一个冠状病毒跟踪网站,但无法在 HTML 文件中自动更新数据。这是我的 JS 代码:

数据仅在我刷新页面时更改,我怎样才能使其自动更新而无需刷新页面?我认为由于变量在更新函数中,它们会自动更改。我必须在我的 HTML 代码中调用该函数吗?我已经坚持了很长时间,非常感谢您的帮助。我还是 JQuery 的新手,所以这可能是一个简单的解决方法。谢谢

标签: javascripthtmljquery

解决方案


我认为你的代码工作得很好。您看不到任何更新,因为

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()是这样的函数 -toLocaleString('en-US')做同样的事情(以及更多)


推荐阅读