简体   繁体   English

在 JavaScript 中使用 fetch() 时,如何将返回的 object 中的详细信息渲染到 html 页面上

[英]When using fetch() in JavaScript how do I render details from the returned object onto the html page

I'm using fecth() with JSON to get some details from a 3rd party API.我正在使用 fecth() 和 JSON 从第 3 方 API 获取一些详细信息。 I then want to display these details in my html so they render on the page.然后我想在我的 html 中显示这些详细信息,以便它们在页面上呈现。

The API I am using returns details about ski resorts, for example, the resort name, weather conditions and other details.我正在使用的 API 返回有关滑雪胜地的详细信息,例如,度假村名称、天气状况和其他详细信息。

This is my fetch()这是我的 fetch()

async function loadResortName() {
      const response = await fetch('https://api.fnugg.no/search?q=Harpefossen',{
            headers: {
                //'Accept': 'application/json'
            },
            dataType: "json",
      });
      const resortName = await response.json();
        console.log(resortName);
        document.getElementById('test1').innerHTML = resortName.name
      }
      loadResortName();
<div id="test1">
   [resort name should display here]             
</div>

The console.log returns a complex javascript object that seems to contain nested objects and arrays. console.log 返回一个复杂的 javascript object,它似乎包含嵌套对象和 arrays。 I need to be able to render in html on the page:我需要能够在页面上的 html 中呈现:

  1. The resort name度假村名称
  2. the wind name, mps and speed风名、mps 和速度
  3. condition_description条件描述
  4. The weather symbol天气符号

This is a screen shot from the console of how the object returns.这是 object 如何返回的控制台屏幕截图。 As you can see these details are nested down within the object, but I can't figure out how to access them and render them on the html page, can anyone give me an example of how to do this?如您所见,这些详细信息嵌套在 object 中,但我不知道如何访问它们并在 html 页面上呈现它们,谁能给我一个如何执行此操作的示例? with my limited knowledge I thought I'd just be able to do something like resortName.name but this fails.以我有限的知识,我以为我只能做类似 ResortName.name 的事情,但这失败了。

在此处输入图像描述

As you mentioned "https://api.fnugg.no/search?q=Harpefossen" returns more than just the resort name.正如您提到的“https://api.fnugg.no/search?q=Harpefossen”返回的不仅仅是度假村名称。 The response contains all the data that you need.响应包含您需要的所有数据。

const resp = await fetch('https://api.fnugg.no/search?q=Harpefossen')
const data = await resp.json()
data.hits.hits[0]._source.name // hotel name
data.hits.hits[0]._source.conditions.current_report // weather report

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

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