这个问题在这里已有答案:
我正在尝试使用Javascript fetch api并输出收到的json
我有一个例子here但我无法显示任何东西
我不知道在哪里看。任何人都可以指出正确的方向
let output
const fetchData = async () => {
const api_call = await fetch('https://jsonplaceholder.typicode.com/posts')
const data = await api_call.json();
return{data}
}
const showData = () => {
fetchData()
.then((res) => {
console.log(res.title)
output +=
`<div>
<ul>
<li>Title: ${res.title}</li>
<li>Body: ${res.body}</li>
</ul>
</div>`;
})
document.getElementById('root').innerHTML = output
}
showData()
它确实有效,我认为你的代码有点不稳定。看到这个片段:
const fetchData = () =>
fetch('https://jsonplaceholder.typicode.com/posts')
.then(res => res.json());
fetchData().then(res => {
let output;
res.forEach(r => {
output += `<div>
<ul>
<li>Title: ${r.title}</li>
<li>Body: ${r.body}</li>
</ul>
</div>`;
});
document.getElementById('root').innerHTML = output;
});
<div id="root"></div>
两个主要问题是:
{ data }
返回fetchData()
的方式。这应该重写为return data;
以确保直接返回数组fetchData()
返回的数据需要被视为一个数组。在.then()
块中,可以使用for .. of
循环迭代,并将fetchData()
响应中的所有数据格式化为HTML,用于“root”divlet output
const fetchData = async() => {
const api_call = await fetch('https://jsonplaceholder.typicode.com/posts')
const data = await api_call.json();
/* Remove the { and } from around data */
return data
}
const showData = () => {
/* The json data is an array which we'll call rows */
fetchData().then((rows) => {
let output = '';
/* Iterate each row of rows array and add item data to output */
for (const row of rows) {
output +=
`<div>
<ul>
<li>Title: ${row.title}</li>
<li>Body: ${row.body}</li>
</ul>
</div>`;
}
/* Populate dom with generated html */
document.getElementById('root').innerHTML = output;
})
}
showData()
<div id="root"></div>
您的代码中存在两个问题。
1.
.then((res) => {}
返回一个对象。该对象的实际数据是res.data,它是一个包含100个元素的数组。要获得所有元素,必须使用for循环迭代它。
for (var a = 0; a < res.data.length; a++) {
// handle data here
title = res.data[a].title; // for example the title
}
2.在迭代完这个数组之后,你应该更新根DIV。在json数据可用之前,您正在更新它。
这是完整的例子:
let output
const fetchData = async () => {
const api_call = await fetch('https://jsonplaceholder.typicode.com/posts')
const data = await api_call.json();
return {
data
}
}
const showData = () => {
fetchData()
.then((res) => {
for (var a = 0; a < res.data.length; a++) {
output +=
`<div>
<ul>
<li>Title: ${res.data[a].title}</li>
<li>Body: ${res.data[a].body}</li>
</ul>
</div>`;
}
document.getElementById('root').innerHTML = output;
})
}
showData()
<div id="root"></div>