为了账号安全,请及时绑定邮箱和手机立即绑定

如何从网站获取 api 数据,它显示 TypeError 消息

如何从网站获取 api 数据,它显示 TypeError 消息

蛊毒传说 2022-06-09 16:37:16
function getInfo() {  fetch("https://swapi.co/api/people")    .then(response => response.json())    .then(function(data) {      console.log(data);    })    .catch(function(error) {      // If there is any error you will catch them here      console.log(error);    });}const newPerson = document.getElementById('newQuote')newPerson.addEventListener('click', getInfo); // new quote on button clickwindow.onload = getInfo; // new quote on page load我编写了这段代码并在控制台中收到以下消息:TypeError{}
查看完整描述

1 回答

?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

您不应将该async函数用作事件侦听器的函数。您应该做的是async在侦听器函数中调用该函数。


function getInfo() {

  fetch("https://swapi.co/api/people")

    .then(response => response.json())

    .then(function(data) {

      console.log(data);


    })

    .catch(function(error) {

      // If there is any error you will catch them here

      console.log(error);

    });

}




const newPerson = document.getElementById('newQuote');


newPerson.addEventListener('click', function(e) {

    e.preventDefault();

    getInfo();

});


window.addEventListener('load', function(e) {

    getInfo();

});

<button id="newQuote">New Quote</button>


查看完整回答
反对 回复 2022-06-09
  • 1 回答
  • 0 关注
  • 137 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号