首页 > 解决方案 > 尝试从 API 解析和存储 JSON 数据时如何知道目标是什么

问题描述

所以我对 javascript 比较陌生,并且在 API 链接中遵循了本教程,但有一件事我很困惑。

这是我的代码,

const app = document.getElementById('root');

const logo = document.createElement('img');
logo.src = 'logo.png';

const container = document.createElement('div');
container.setAttribute('class', 'container');

app.appendChild(logo);
app.appendChild(container);

var request = new XMLHttpRequest();
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true);
request.onload = function () {

  // Begin accessing JSON data here
  var data = JSON.parse(this.response);
  if (request.status >= 200 && request.status < 400) {
    data.forEach(movie => {
      const card = document.createElement('div');
      card.setAttribute('class', 'card');

      const h1 = document.createElement('h1');
      h1.textContent = movie.title;

      const p = document.createElement('p');
      movie.description = movie.description.substring(0, 300);
      p.textContent = `${movie.description}...`;

      container.appendChild(card);
      card.appendChild(h1);
      card.appendChild(p);
    });
  } else {
    const errorMessage = document.createElement('marquee');
    errorMessage.textContent = `Gah, it's not working!`;
    app.appendChild(errorMessage);
  }
}

request.send();

这是查询 API 的 JSON 数据的链接,将为您提供 https://ghibliapi.herokuapp.com/films/

所以我感到困惑的一件事是这一行,以及包含movie.something的后续行

data.forEach(movie => {

我不明白你为什么要使用“movie”它没有在代码或实际的 JSON 中定义,那么你怎么知道它是“movie.description”而不是“film.description”之类的东西?我敢肯定,如果我能弄清楚这一点,那将是使用其他 API 并引用它们的数据的关键。

谁能帮我?

(另外,这里是实际的 API 文档,https://ghibliapi.herokuapp.com/#

标签: javascript

解决方案


movie是箭头函数的参数。它几乎可以被称为任何你想要的东西。data是一个数组,所以forEach可用。

那条线就像data.forEach(function(movie) { ... }.bind(this));


推荐阅读