HTML页面JS代码可获取RESTful API数据但无法渲染数组对象如何解决
问题修复说明
你的代码存在3处逻辑错误,对应修改方案如下:
- 接口返回的
country.name为嵌套对象,并非直接的国名字符串,直接赋值给innerHTML会渲染为[object Object],需取country.name.common获取国家常用名 - v3.1版本的restcountries接口国旗资源存放在
country.flags.png/country.flags.svg字段下,不存在顶层country.flag属性,会导致图片加载失败 - 你创建了国旗img元素,但没有将其追加到国家卡片DOM中,图片永远不会被渲染到页面
修正后完整代码
<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.common // 赋值正确的国旗地址 countryCardImage.src = country.flags.png // 把图片追加到卡片中 countryCard.appendChild(countryCardImage) document.getElementById('feed').appendChild(countryCard) }) } } xhr.send() } </script>
如果需要优化显示效果,可以自行给卡片和图片添加CSS样式控制宽高、边距等属性。
内容的提问来源于stack exchange,提问作者Svetlana Gulotta
相关产品推荐
相关产品推荐

