简体   繁体   中英

calling api with Ajax call

I try to call an external api resource.

The api recourse is from this link: https://restcountries.com

And this is the javascript code:

const getCountry = function(country){ 

const btn = document.querySelector(".btn-country");
const countriesContainer = document.querySelector(".countries");

const request = new XMLHttpRequest();
request.open("GET", `https://restcountries.com/v3.1/name/${country}`);
request.send();

//console.log(request.responseText);

request.addEventListener("load", function () {
  //console.log(this.responseText);
  const [data] = JSON.parse(this.responseText);
 // console.log(data);

  const html = `
  <article class="country">
  <img class="country__img" src="${data.flags}" />
  <div class="country__data">
    <h3 class="country__name">${data.name}</h3>
    <h4 class="country__region">${data.region}</h4>
    <p class="country__row"><span>👫</span>${(
      +data.population / 1000000
    ).toFixed(1)} people</p>
    <p class="country__row"><span>🗣️</span>${data.languages}</p>
    <p class="country__row"><span>💰</span>${data.currencies}</p>
  </div>
</article>
    `;
  countriesContainer.insertAdjacentHTML("beforeend", html);
  countriesContainer.style.opacity = 1;
});
}


getCountry('portugal');

And this is the html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="./style.css" />
    <script defer src="./restCountries.js"></script>
    <title>Asynchronous JavaScript</title>
  </head>
  <body>
    <main class="container">
      <div class="countries">
      
      </div>
      <!-- <button class="btn-country">Where am I?</button> -->
      <div class="images"></div>
    </main>
  </body>
</html>

and I see that the data is returned in chrome tools.

But I still get this error:

[object%20Object]:1 GET http://127.0.0.1:5500/jquery/Algorithms/[object%20Object] 404 (Not Found)

So what I have to change?

Thank you

Holy. I am great.

So this works:

  request.open('GET', `https://restcountries.com/v2/name/${country}`);

Thank you for helping :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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