enter image description hereThe problem is that the objects of the API are not being rendered in HTML, what did I do wrong?
<button onclick = "showCountries()">Show Countries</button>
<div id = "feed"></div>
<script>
function showCountries(){
let xhr = new XMLHttpRequest()
xhr.open('GET', 'https://restcountries.com/v3.1/all', true)
xhr.onload = function(){
if(xhr.status == 200){
console.log('success')
let countries = JSON.parse(this.response)
countries.forEach(country=>{
const countryCard = document.createElement('div')
const countryCardImage = document.createElement('img')
countryCard.innerHTML = country.name
countryCardImage.src = country.flag
document.getElementById('feed').appendChild(countryCard)
})
}
}
xhr.send()
}
</script>
CodePudding user response:
Because country.name
is an object.You should use an string to set the innerHTML of element.
According to your response data structure, you can use it like this:
function showCountries() {
let xhr = new XMLHttpRequest()
xhr.open('GET', 'https://restcountries.com/v3.1/all', true)
xhr.onload = function() {
if (xhr.status == 200) {
console.log('success')
let countries = JSON.parse(this.response)
countries.forEach(country => {
const countryCard = document.createElement('div')
const countryCardImage = document.createElement('img')
countryCard.innerHTML = country.name.common
countryCardImage.src = country.flags.png
countryCardImage.style.width = "30px"
countryCard.append(countryCardImage)
document.getElementById('feed').appendChild(countryCard)
})
}
}
xhr.send()
}
<button onclick="showCountries()">Show Countries</button>
<div id="feed"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
I finally figured out how to display flags, here is the source:
function showCountries(){
let xhr = new XMLHttpRequest()
xhr.open('GET', 'https://restcountries.com/v3.1/all', true)
xhr.onload = function(){
if(xhr.status == 200){
console.log('success')
let countries = JSON.parse(this.response)
countries.forEach(country=>{
const countryCard = document.createElement('div')
const countryCardImage = document.createElement('div')// must be div to display small image
countryCard.innerHTML = country.name.common
countryCardImage.innerHTML = country.flag
console.log(country.flag)
document.getElementById('feed').appendChild(countryCard)
document.getElementById('feed').appendChild(countryCardImage) //this is it!
})
}
}