javascript - 尝试从 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/#)
解决方案
movie
是箭头函数的参数。它几乎可以被称为任何你想要的东西。data
是一个数组,所以forEach
可用。
那条线就像data.forEach(function(movie) { ... }.bind(this));
推荐阅读
- ios - 使用 swift 在标签栏中制作弯曲和曲线
- python - Python中的非对称高斯拟合
- node.js - PassportJs / Oauth / GoogleStrategy 的注销问题
- count - How do I automatically break line within a cell in a LaTeX table containing counts and percentage
- javascript - 带按钮的简单计算器不起作用
- javascript - dotenv API 凭据字符串或不加引号
- xcode - 使用 swiftUI 从服务器内部图像滑块加载图像
- android - HorizontalPicker Error in Arabic Language
- php - Session not save after redirect in WordPress
- python - 使用 Flask 链接一个简单的 SQLite 数据库