简体   繁体   English

使用从 API 中提取的数据

[英]Using data pulled from an API

It's been half a day now of trying to figure this out, and while some progress has been made, and a ton of useful research, I'm still a newbie so I need help.尝试解决这个问题已经半天了,虽然已经取得了一些进展,并且进行了大量有用的研究,但我仍然是新手,所以我需要帮助。

What I need is to use the data that I'm pulling from an API to use as a JS variable.我需要使用从 API 中提取的数据用作 JS 变量。 My API is giving me the following output:我的API给了我以下 output:

{"bitcoin":{"usd":9695.66,"usd_24h_change":2.0385849528977977}}

I want to use the usd and usd_24_change values from that string, maybe as some JS variable for further calculations.我想使用该字符串中的usdusd_24_change值,可能作为一些 JS 变量进行进一步计算。

So far what I've managed to do was to push the string directly in HTML, so I can have a visual representation of it, however I need to pull the values from it in the backend (hope that makes sense?)到目前为止,我设法将字符串直接推送到 HTML 中,这样我就可以对其进行可视化表示,但是我需要在后端从中提取值(希望这有意义吗?)

My code so far:到目前为止我的代码:

 fetch(url).then(response => response.text()).then(data => { $('#apiPlaceholder').html(data); });

I've honestly ran out of ideas.老实说,我已经没有想法了。 My only alternative would be trying to pull the values directly from the HTML string but I feel like that would be a really clunky way of doing it.我唯一的选择是尝试直接从 HTML 字符串中提取值,但我觉得这将是一种非常笨拙的方法。 I'm sure there's ways to interpret the data in the backend.我确信有办法解释后端的数据。

Any ideas would definitely be appreciated: :)任何想法都将不胜感激::)

Here's how you would go about doing that:以下是 go 关于这样做的方法:

fetch(url)
  .then(response => response.json())
  .then(data => {
    console.log(data["bitcoin"]["usd"]);
    console.log(data["bitcoin"]["usd_24h_change"]);
  });

you need to parse the response and then just save it.您需要解析响应,然后保存它。

 fetch(url)
  .then(response => response.text())
  .then(data => {
    const parsedData = JSON.parse(data);
    const usd = parsedData.bitcoin.usd;
    const usd_24h_change = parsedData.bitcoin.usd_24h_change;
  });

or display it instead;或改为显示它;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM