![](/img/trans.png)
[英]Failing to display data correctly fetched from Json file with Javascript .innerHTML()
[英]cannot display fetched data in my javascript file
我有一個 json 文件,我獲取了數據。 但是我無法在屏幕上顯示它。 如何顯示? 我在控制台中獲得了數據結果,但是我無法訪問產品名稱、價格等參數。
我的代碼如下
index.html
<body>
<div id="products"></div>
<script src="/index.js"></script>
</body>
index.js
fetch("./data.json")
.then(response => {
return response.json();
})
.then(data => console.log(data));
showProducts = products => {
const showProductsDiv = document.querySelector("#products");
products.map(product => {
const productElement = document.createElement("p");
productElement.innerText = `product Name: ${product.name}`;
showProductsDiv.append(productElement);
});
}
我還分享控制台結果
您需要使用您的showProducts
function。 下面是一個示例代碼,它也適用於您,但請記住,我使用了一個示例 api。 這與你的有點不同,這就是為什么我有results
數組和name.first
。
const url = 'https://randomuser.me/api/?results=10';
fetch(url)
.then((resp) => resp.json())
.then(data => {
return showProducts(data)
})
showProducts = products => {
const showProductsDiv = document.querySelector("#products");
products.results.map(product => {
const productElement = document.createElement("p");
productElement.innerText = `product Name: ${product.name.first}`;
showProductsDiv.append(productElement);
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.