亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從網站獲取 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 關注
  • 151 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號