[英]My Javascript JSON code in HTML page does not render the RESTful API array objects, although I get the data from the API. What should I do?
enter image description here The problem is that the objects of the API are not being rendered in HTML, what did I do wrong?在此处输入图像描述问题是 API 的对象没有在 HTML 中呈现,我做错了什么?
<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>
Because country.name
is an object.You should use an string to set the innerHTML of element.因为
country.name
是 object。您应该使用字符串来设置元素的 innerHTML。 According to your response data structure, you can use it like this:根据您的响应数据结构,您可以像这样使用它:
countryCard.innerHTML = country.name.common; // or any other property
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!
})
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.