我正在尝试使用API https://api.got.show/api/general/characters/从《权力的游戏》(显示)中选择所有角色名称。我尝试了多种方法,但所有方法都失败了。现在,当我尝试使用其他API并可以正常工作时,它说“ TypeError:无法读取未定义的属性'forEach'”。我不知道该怎么办。到目前为止,这是我的代码:
<body>
<h1>Game of thrones</h1>
<select>
<option id="characters"></option>
</select>
<script>
fetch('https://api.got.show/api/general/characters/')
.then(data => data.json())
.then(data_json => {
console.log(data_json)
show(data_json)
})
.catch(err => alert(`Ha habido un error. ${err}`))
let show = data_json => {
data_json.results.forEach((element, index) => {
document.getElementById('characters').innerHTML += `<option class""character">${element.name}</option>`;
});
}
</script>
</body>
答案 0 :(得分:1)
我尝试自己调用API。看起来data_json
具有两个属性book
和show
,但没有results
。
尝试使用以下代码段来代替show
函数:
let show = data_json => {
data_json.show.forEach((element, index) => {
document.getElementById('characters').innerHTML += `<option class="character">${element.name}</option>`;
});
}