嗨,我一直在尝试使用获取链从两个API进行获取,获取工作正常,并且使用getallproducts函数中的console.log正确显示了数据,但是当我尝试使用数据对displayproducts函数进行回调时,数据无处可寻。我不确切知道我在做什么错,或者我是否为此使用了错误的方法,但是我一直在尝试多种提取方法。 promise.all似乎都是解决方案,但这也不起作用。
showProductsPage函数
function showProductsPage() {
var page = document.getElementById('products-page');
hideAllPages();
//getAllProducts();
displayproducts(getAllProducts);
page.style.display = 'block';
}
getallproducts功能
function getAllProducts(callback){
var producten;
var authors;
fetch(window.location.href+"api/products")
.then(response => response.json())
.then(data => {
producten = data.products;
console.log(data);
callback(data)
return fetch(window.location.href+"api/authors")
}).then(response => response.json())
.then(data => {
authors = data.authors;
callback(data)
})
}
显示产品功能
function displayproducts(data) {
console.log(data.products);
for (var i = 0; i < data.products.length; i++) {
var card = document.createElement("div");
var img = document.createElement("img");
var name = document.createElement("BUTTON");
var author = document.createElement("p");
var published = document.createElement("p");
var price = document.createElement("p");
var cart = document.createElement("BUTTON");
document.getElementById("products-page").appendChild(card);
//
card.appendChild(img);
card.appendChild(name);
card.appendChild(author);
card.appendChild(published);
card.appendChild(price);
card.appendChild(cart);
//
card.setAttribute("class", "book-card");
img.setAttribute("class", "product-img");
name.setAttribute("class", "book-title");
author.setAttribute("class", "author");
published.setAttribute("class", "published");
price.setAttribute("class", "price");
cart.setAttribute("class", "add-to-cart");
//
cart.innerHTML = "Add to Cart";
name.innerHTML = data.products.title;
price.innerHTML = data.products.price;
};
//console.log(producten[1].price);
}
答案 0 :(得分:0)
您将通话混为一谈。这个:
displayproducts(getAllProducts)
必须是:
getAllProducts(displayproducts);