繁体   English   中英

My Javascript JSON code in HTML page does not render the RESTful API array objects, although I get the data from the API. 我应该怎么办?

[英]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.

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