问题描述
json 文件:
[
{
"name": "The Starry Night",
"year": "1889",
"artist": "Vincent Van Gogh"
},
{
"name": "The Scream",
"year": "1893",
"artist": "Edvard Munch"
},
{
"name": "Guernica",
"year": "1937",
"artist": "Pablo Picasso"
}
]
html:
<html>
<head>
</head>
<body>
<h2>Some famous paintings</h2>
<table id="paintings">
<tr>
<th>Name</th>
<th>Year</th>
<th>Artist</th>
</tr>
</table>
</body>
</html>
解决方法
??????? 我的:
//Write-Your-Code-Here
fetch(
"https://raw.githubusercontent.com/bpesquet/thejsway/master/resources/paintings.json"
)
.then(reponse => reponse.json())
.then(paintings => {
paintings.forEach(painting =>{
const tableElement = document.getElementById("paintings");
const trElement = document.createElement("tr") ;
const nameElement = ducument.createElement("th");
const yearElement = document.createElement("th");
const artistElement = document.createElement("th");
yearElement.textContent = painting.year;
artistElement.textContent = painting.artist;
nameElement.textContent = painting.name;
trElement.appendChild(nameElement);
trElement.appendChild(yearElement);
trElement.appendChild(artistElement);
tableElement.appendChild(trElement);
});
})
.catch(err =>
{
console.log(err.message);
});
参考答案:
fetch(
"https://raw.githubusercontent.com/bpesquet/thejsway/master/resources/paintings.json"
)
.then(response => response.json()) // Access and return response's JSON content
.then(paintings => {
const paintingsElement = document.getElementById("paintings");
paintings.forEach(painting => {
const paintingElement = document.createElement("tr");
paintingElement.innerHTML = `<td>
${painting.name}
</td>
<td>
${painting.year}
</td>
<td>
${painting.artist}
</td>`;
paintingsElement.appendChild(paintingElement);
});
})
.catch(err => {
console.error(err.message);
});
|