[英]calling api with Ajax call
我嘗試調用外部 api 資源。
api 資源來自此鏈接: https : //restcountries.com
這是 javascript 代碼:
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');
這是 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>
我看到數據是在 chrome 工具中返回的。
但我仍然收到此錯誤:
[object%20Object]:1 GET http://127.0.0.1:5500/jquery/Algorithms/[object%20Object] 404 (Not Found)
那我必須改變什么?
謝謝
聖。 我很好。
所以這有效:
request.open('GET', `https://restcountries.com/v2/name/${country}`);
感謝您的幫助 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.