【问题标题】:Why am I getting undefined as an answer when fetching data from an api?为什么从 api 获取数据时我得到未定义的答案?
【发布时间】:2019-04-11 13:28:44
【问题描述】:

我正在学习如何使用 fetch api,并且我正在尝试打印 Simpsons api 的报价作为练习。问题在于,答案一直是不确定的。你知道为什么它不只是打印报价吗?

let button    = document.querySelector('#button')
let quote      = document.querySelector('#quote')

function getInfoFetch(){

  fetch('https://thesimpsonsquoteapi.glitch.me/quotes')
    .then(response => response.json())
    .then((data) => {

      quote.innerText = data.quote;

    })
    .catch(err => console.log(err));
}

button.addEventListener('click', getInfoFetch)

【问题讨论】:

  • data[0].quote - 因为在这种情况下数据是一个数组
  • 这应该是一个答案:P。
  • 我做到了,然后我意识到只需 3 秒的调试时间就可以解决这样一个基本问题@zozo - 所以我删除了答案

标签: javascript ajax api fetch


【解决方案1】:

API 的响应似乎是一个数组,这意味着您需要从数组响应的第一项访问报价数据。

您可以通过对代码进行以下更改来做到这一点:

let button = document.querySelector('#button')
let quote = document.querySelector('#quote')

function getInfoFetch(){

  fetch('https://thesimpsonsquoteapi.glitch.me/quotes')
    .then(response => response.json())
    .then((data) => {
    
      // Access first item of data "array" to retrieve and display quote
      quote.innerText = data[0].quote;

    })
    .catch(err => console.log(err));
}

button.addEventListener('click', getInfoFetch)
<button id="button">Get quote</button>
<div id="quote"></div>

【讨论】:

    【解决方案2】:

    第二个.then的数据是一个数组,里面有一个对象。 如果要获取对象中的quote,需要使用data[0]选择对象。然后,使用.quote选择对象中的键quote。并且可以得到你想要的价值。

    let button = document.querySelector('#button');
    let quote = document.querySelector('#quote');
    
    function getInfoFetch(){
      fetch('https://thesimpsonsquoteapi.glitch.me/quotes')
        .then(response => response.json())
        .then((data) => {
          console.log(data); 
          //this is an array with object(index = 0) inside [{...}]
          quote.innerText = data[0].quote;
        })
        .catch(err => console.log(err));
    }
    
    button.addEventListener('click', getInfoFetch);
    

    【讨论】:

      【解决方案3】:

      你正在解析的数据是数组类型

      [{"quote":"I can't even say the word 'titmouse' without gigggling like a schoolgirl.","character":"Homer Simpson","image":"https://cdn.glitch.com/3c3ffadc-3406-4440-bb95-d40ec8fcde72%2FHomerSimpson.png?1497567511939","characterDirection":"Right"}]
      

      所以要阅读你也需要传递索引

      fetch('https://thesimpsonsquoteapi.glitch.me/quotes')
          .then(response => response.json())
          .then((data) => {
      
            quote.innerText = data[0].quote;
      
          })
          .catch(err => console.log(err));
      

      这里是working fiddle

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多