首页 > 解决方案 > 从 api 调用中检索到的数据更新 html

问题描述

我是网络开发新手,所以请原谅。

我做了简单的 api 调用

  const getWorldTotal = async () => {
  const response = await fetch('https://cors-anywhere.herokuapp.com/https://health-api.com/api/v1/covid-19/total');
  const worldTotal = await response.json();
  alert(worldTotal.total_confirmed)
  document.getElementById('total') = worldTotal.total_confirmed
};
getWorldTotal()

这是我正在尝试更新的 html

<div class="card text-white bg-secondary mb-3" id="total" style="max-width: 20rem;">
<div class="card-header">Header</div>
<div class="card-body">
  <h4 class="card-title" id="total"></h4>
</div>
</div>

我收到以下错误

index.html:80 Uncaught (in promise) ReferenceError: Invalid left-hand in assignment at getWorldTotal

我的问题是我做错了什么?这也是进行 api 调用时更新 HTML 的最佳方式吗?

标签: javascripthtml

解决方案


Document 方法 getElementById() 返回一个 Element 对象,您正在尝试更改它,这会给您带来错误。
来源 。此外,如果您想更改文本,您可以使用 innerText

  const getWorldTotal = async () => {
  const response = await fetch('https://cors-anywhere.herokuapp.com/https://health-api.com/api/v1/covid-19/total');
  const worldTotal = await response.json();
  alert(worldTotal.total_confirmed)
  document.getElementById('total').innerText = worldTotal.total_confirmed
};

getWorldTotal()

推荐阅读