【发布时间】:2021-03-27 11:41:11
【问题描述】:
我正在尝试学习如何将数据从 API 获取到 JSON 数据的多个级别,但我对如何做到这一点感到困惑。例如,我正在尝试创建一个随机膳食生成器,它显示一组食谱中的成分列表,而且我需要的成分名称在它们自己的对象中。
我不知道如何设置我的循环以遍历列表并获取成分名称以显示它。到目前为止,这是我的示例:codepen
谢谢!
document.getElementById("shuffle").addEventListener('click', getImage);
async function getImage() {
const response = await fetch("https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/random?number=1", {
"method": "GET",
"headers": {
"x-rapidapi-key": "{redacted}",
"x-rapidapi-host": "spoonacular-recipe-food-nutrition-v1.p.rapidapi.com"
}
})
const data = await response.json();
document.getElementById('title').innerHTML = data.recipes[0]["title"];
document.getElementById('instructions').innerHTML = data.recipes[0]["instructions"];
document.getElementById('image').src = data.recipes[0]["image"];
show(data);
}
getImage()
.catch(error => {
console.error(error);
});
function show(data) {
let list =
`
<ul></ul>
`
for (let ingredient of data.recipes) {
list += `
<li>${ingredient.extendedIngredients[0].originalString}</li>
`;
}
document.getElementById('ingredients').innerHTML = list;
}
.recipe {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
text-align: center;
}
.recipe__directions {
display: flex;
width: 50vw;
margin: 2rem;
}
.recipe__instructions {
text-align: left;
margin-right: 1rem;
}
.recipe__image {
width: 25vw;
margin-left: 1rem;
}
<html>
<head>
<!-- Material Design Lite -->
<script src="https://code.getmdl.io/1.3.0/material.min.js"></script>
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
<!-- Material Design icon font -->
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
</head>
<body>
<section class="recipe">
<h1>Feeling hungry?</h1>
<h2>Get a random meal by clicking below</h2>
<button class="button mdl-button mdl-js-button mdl-button--raised mdl-button--colored" id="shuffle">Find a meal</button>
<h3 id="title" class="recipe__title"></h3>
<div id="ingredients" class="recipe__ingredients"></div>
<div class="recipe__directions">
<p id="instructions" class="recipe__instructions"></p>
<img id="image" class="recipe__image" src="" alt="">
</div>
</section>
</body>
</html>
【问题讨论】:
-
代码看起来已经很不错了,但是如果没有看到来自 API 的示例响应,很难说出您需要做什么。
-
(一般来说,在互联网上发布 API 密钥并不是一个好主意。)
标签: javascript arrays json for-loop object