如何将来自 fetch(url) 的数据显示为变量,我可以将其放入特定的容器元素中

问题描述 投票:0回答:0

我有一个从 url 获取数据的函数,然后每 x 秒 ping 一次 url 以获取更新的数据。我从 fetch(url) 获取数据,然后将响应转换为可读的 json 文件。过去这两个步骤是我感到困惑的地方。我熟悉的唯一显示 json 数据的方法是使用 document.querySelector() 输出我的 fetch(url) 数据。我半理解我的“document.querySelector”正在我的 htmls 主体中显示数据,我只是不确定如何将该数据从这个函数导出到我可以根据需要在元素和样式中使用的东西。

let foundationUrl = "https://api.binance.us/api/v3/ticker/price?symbol=";

function createPriceFed(foundationUrl, ticker1, ticker2) {
  var url = foundationUrl + ticker1 + ticker2;
  return url;
}
async function repeatedPinging() {
  var url = createPriceFed(foundationUrl, "BTC", "USD");
  let response = await fetch(url);
  if (response.ok) {
    let json = await response.json();
    if (
      typeof document != "undefined" &&
      typeof document != "[object Object]"
    ) {
      document.querySelector("body").innerHTML =
        json["symbol"] + " : " + json["price"];
    }
  } else {
    alert("HTTP-Error " + response.text);
  }
  setTimeout(repeatedPinging, 8000);
}
repeatedPinging();

我尝试在我的网页上显示我的数据,它按预期工作,我只是想将该数据作为可导出变量获取,我可以根据需要插入容器元素和样式

javascript html frontend fetch document
© www.soinside.com 2019 - 2024. All rights reserved.