使用提取的API-无法读取未定义的属性'forEach'

时间:2020-05-30 11:43:25

标签: json api foreach fetch-api

我正在尝试使用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>

1 个答案:

答案 0 :(得分:1)

我尝试自己调用API。看起来data_json具有两个属性bookshow,但没有results

尝试使用以下代码段来代替show函数:

let show = data_json => {
  data_json.show.forEach((element, index) => {
    document.getElementById('characters').innerHTML += `<option class="character">${element.name}</option>`;
  });
}