使用JavaScript在HTML页面上显示API请求的结果

发布于 2025-02-09 18:02:57 字数 1884 浏览 0 评论 0原文

我必须构建一个页面,其中使用API​​显示国家(例如名称,人口等)的信息。我设法使用fetch在控制台上显示了请求结果,但我不知道如何在HTML页面中显示结果。我是初学者,非常不经验。我几乎不知道JS。

我已经看到了其他这样的主题,但它们并没有真正帮助解决我的问题。其中一个有一个答案,提出了以下代码,直到JS脚本的第7行都很好。但是,在添加了其余代码后,我会收到一个错误,说untuffing(Promise)TypeError:数据是未定义的。我不明白为什么它以前使用该数据是不确定的。

function displayAll() {
  let countriesList = [];
  let url = "https://restcountries.com/v3.1/all";

  fetch(url).then(function(response){
    response.json().then(function(data) {
      console.log(data);  // works fine up until here
    })
    .then((data) => { // error says that 'data' is undefined
      let countries = document.getElementById("countries-container");
      data.results.forEach((item) => {
        countriesList.push(item.name);
        let div = document.createElement("div");
        div.innerText = item.name;
        countries.appendChild(div);
      })
      console.log(countriesList)
    })
  });
}
<body onload="displayAll()">

  <header>Countries</header>
  
  <div class="container" id="countries-container">
  
    <!-- This is where the results will be displayed -->
  
  </div>

  <script src="./assets/scripts.js"></script>
  
</body>

我想添加新元素作为卡(每个国家 /地区)。

有些事情告诉我,会有更多的错误,因为在控制台中印刷的结果似乎太复杂了,因为它似乎是矩阵:

“请求结果的snipet”

sstatic.net/4tbnz.png“ rel =“ nofollow noreferrer”> < m不使用任何框架,因为我仍然需要在跳入更美好的东西之前了解更多有关基础知识的信息。代码只是HTML,CSS和JavaScript,如果可能的话,我想保持这种方式。我尝试学习反应Alreaddy,我认为我还没有准备好...无论如何,如果有人可以帮助我,我将非常感谢。

I have to build a page where the infos of countries (such as name, population, etc) are displayed using an API. I have managed to show the request results on the console using fetch, but I don't know how to display the results in the HTML page. I'm a beginner and very unexperienced. I know very little js.

I've seen other topics like this one, but they didn't really help solve my problem. One of them had an answer that suggested a code like the following, which worked fine until line 7 of the js script. However after adding the rest of the code I get an error that says Uncaught (in promise) TypeError: data is undefined. I don't understand why it says data is undefined when it has been used before.

function displayAll() {
  let countriesList = [];
  let url = "https://restcountries.com/v3.1/all";

  fetch(url).then(function(response){
    response.json().then(function(data) {
      console.log(data);  // works fine up until here
    })
    .then((data) => { // error says that 'data' is undefined
      let countries = document.getElementById("countries-container");
      data.results.forEach((item) => {
        countriesList.push(item.name);
        let div = document.createElement("div");
        div.innerText = item.name;
        countries.appendChild(div);
      })
      console.log(countriesList)
    })
  });
}
<body onload="displayAll()">

  <header>Countries</header>
  
  <div class="container" id="countries-container">
  
    <!-- This is where the results will be displayed -->
  
  </div>

  <script src="./assets/scripts.js"></script>
  
</body>

I want to add new elements to serve as cards (one for each country).

Something tells me there will be more errors because the results printed in the console seem a bit too complicated to iterate, since it seems to be a matrix:

snipet of request result

snipet of request result expanded

I'm not using any frameworks, since I still need to learn more about the basics before jumping into the more fancy stuff. The code is just HTML, CSS and JavaScript and I want to keep it that way if possible. I've tried learning React alreaddy and I think I'm not ready yet... Anyway, if anybody can help me with this, I'll be very grateful.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

所谓喜欢 2025-02-16 18:02:57

我已经解决了问题。添加返回数据到第一个。未定义的(读取)。我从data.results.foreach删除结果后,此错误消失

了] 和json.parse()会在原始数据中某个地方某个地方出现另一个错误。因此,我意识到我必须创建HTML元素才能在页面中显示数据。很明显,我知道。但是正如我所说:我是一个总体初学者。

因此,考虑到这一点,我创建了以下代码,并且效果很好!
原来,我并不需要所有国家的清单,所以我从代码中消除了这些清单。

// Searches and shows the data of all the countries in the homepage upon loading

function displayAll() {
  let url = "https://restcountries.com/v3.1/all";

  fetch(url).then(function(response){
    response.json().then(function(data) {
      console.log(data);
      return data;
    })
    .then((data) => {      
      data.forEach((item) => {
        showCountryHome(item);
      })
    })
  });
}

// Creates a card for each country with the information I want

function showCountryHome(data) {
  let countries = document.getElementById("countries-wrapper");
  let div = document.createElement("div");
  div.className = "card";
  div.innerHTML = `<img src="${data.flags.svg}" width=200>
                   <p>${data.name.common}</p>
                   <p>Population: ${data.population}</p>
                   <p>Region: ${data.region}</p>
                   <p>Capital: ${data.capital}</p>`
  countries.appendChild(div);
}

I've managed to solve the problem. Adding return data to the first .then solved the data undefined error, but then I got another error: TypeError: cannot read properties of undefined (reading forEach). This error disappeared after I deleted results from data.results.forEach

I could finally make the data appear in the HTML page, but it was shown as [object Object] and JSON.parse() would thow another error about an unexpected character somewhere in the original data. So I realized that I had to create the HTML elements to be able to show the data in the page. Obvious, I know. But as I said: I'm a total beginner.

So with that in mind, I created the following code and it works just fine!
Turns out I didn't really need a list of all the countries, so I eliminated that from the code.

// Searches and shows the data of all the countries in the homepage upon loading

function displayAll() {
  let url = "https://restcountries.com/v3.1/all";

  fetch(url).then(function(response){
    response.json().then(function(data) {
      console.log(data);
      return data;
    })
    .then((data) => {      
      data.forEach((item) => {
        showCountryHome(item);
      })
    })
  });
}

// Creates a card for each country with the information I want

function showCountryHome(data) {
  let countries = document.getElementById("countries-wrapper");
  let div = document.createElement("div");
  div.className = "card";
  div.innerHTML = `<img src="${data.flags.svg}" width=200>
                   <p>${data.name.common}</p>
                   <p>Population: ${data.population}</p>
                   <p>Region: ${data.region}</p>
                   <p>Capital: ${data.capital}</p>`
  countries.appendChild(div);
}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文