因此,我终于有了Star Wars API,以显示来自JSON数组的“人”对象中每个人物的名称,该JSON数组来自Vanilla Javascript中的https://swapi.co/api/people/。但是,我需要根据特定值对数据结果进行排序或过滤,该特定值是https://swapi.co/api/species/1/我当前拥有的代码,运行时它会显示带有以下名称的表所有物种的人,我只需要人类的物种。这是我的代码:
const url = 'https://swapi.co/api/species/1/?format=json';
function fetchData(url) {
return fetch(url).then((resp) => resp.json());
}
function constructTableRow(data) {
const row = document.createElement('tr');
const {
name,
height,
mass,
hair_color
} = data;
row.appendChild(constructElement('td', name))
row.appendChild(constructElement('td', height))
row.appendChild(constructElement('td', mass))
row.appendChild(constructElement('td', hair_color))
return row;
}
function constructElement(tagName, text, cssClasses) {
const el = document.createElement(tagName);
const content = document.createTextNode(text);
el.appendChild(content);
if (cssClasses) {
el.classList.add(...cssClasses);
}
return el;
}
const swTable = document.getElementById('sw-table').getElementsByTagName('tbody')[0];
fetchData('https://swapi.co/api/people/').then((data) => {
data.results.forEach(result => {
const row = constructTableRow(result);
swTable.appendChild(row);
});
});
<table id=sw-table><tbody></tbody></table>
JSON端点来自https://swapi.co/api/people/
如何获得仅显示人类物种数据的表格?
物种API返回的JSON包含一个people
数组。因此,而不是过滤people
,而是遍历people数组。
但是,由于SWAPI速率限制,这可能会引起问题。
const url = 'https://swapi.co/api/species/1/?format=json';
function fetchData(url) {
return fetch(url).then((resp) => resp.json());
}
function constructTableRow(data) {
const row = document.createElement('tr');
const {
name,
height,
mass,
hair_color
} = data;
row.appendChild(constructElement('td', name))
row.appendChild(constructElement('td', height))
row.appendChild(constructElement('td', mass))
row.appendChild(constructElement('td', hair_color))
return row;
}
function constructElement(tagName, text, cssClasses) {
const el = document.createElement(tagName);
const content = document.createTextNode(text);
el.appendChild(content);
if (cssClasses) {
el.classList.add(...cssClasses);
}
return el;
}
const swTable = document.getElementById('sw-table').getElementsByTagName('tbody')[0];
fetchData(url).then(data =>
data.people.forEach(personUrl =>
fetchData(personUrl).then(result => {
const row = constructTableRow(result);
swTable.appendChild(row);
})
)
);
<table id=sw-table>
<tbody></tbody>
</table>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句