![](/img/trans.png)
[英]I am requesting data from an API. Currently, I am getting data as an array of objects but I'm not able to render output on the browser
[英]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?
在此处输入图像描述问题是 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>
因为country.name
是 object。您应该使用字符串来设置元素的 innerHTML。 根据您的响应数据结构,您可以像这样使用它:
countryCard.innerHTML = country.name.common; // or any other property
我终于想出了如何显示标志,这是源代码:
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.