Почему я получаю неопределенный ответ при получении данных из API? - PullRequest
0 голосов
/ 08 ноября 2018

Я учусь использовать 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)

Ответы [ 3 ]

0 голосов
/ 08 ноября 2018

Данные, которые вы анализируете, имеют тип массива

[{"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));

Вот рабочая скрипка

0 голосов
/ 08 ноября 2018

Данные второго .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);
0 голосов
/ 08 ноября 2018

Ответ 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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...