[英]Why can't I display data from API with searchBar?
所以我有一個 searchBar 從 Google Books API 搜索書籍並在 div 中顯示結果。 但問題是,例如,當我輸入“哈利波特”時,它不會顯示任何內容,但如果我只輸入“哈利”,它會顯示一些書,如下所示:
下面還有大約 10 本書,其中沒有一本包含任何哈利波特書籍。 我不知道如何讓它顯示包含特定單詞的所有結果。
我的javascript代碼:
const searchBar = document.getElementById('search');
searchBar.addEventListener('keyup', (e) =>{ //event for searching books
const searchString = e.target.value;
searchBook(searchString);
console.log(e.target.value);
})
function searchBook(query){ //function for searching books by query
const url = BASE_URL + `${query}` + '&' + API_KEY;
fetch(url)
.then(res => res.json())
.then(books => showBooks(books.items));
}
showBooks = books =>{ //function for displaying books
const main = document.getElementById('book_container');
main.innerHTML = "";
books.forEach(book => {
title = book.volumeInfo.title;
author = book.volumeInfo.authors;
description = book.volumeInfo.description;
img = book.volumeInfo.imageLinks.thumbnail;
const bookEl = document.createElement('div');
bookEl.classList.add('book');
bookEl.innerHTML = `
<div class="book">
<img src="${img}">
<div class="book_info">
<h3>${title}</h3>
<p>${author}</p>
</div>
</div>
`
main.appendChild(bookEl);
});
};
}
它與img = book.volumeInfo.imageLinks.thumbnail;
,但我不知道為什么會顯示,因為有時圖像顯示得很好,有時會彈出此錯誤,盡管我很確定我的屬性已定義。
問題2:
有時還會出現以下錯誤:
因為某些對象可能沒有imageLinks
屬性,在這種情況下可能會發生此錯誤。
解決方案:檢查imageLinks
存在,然后只顯示縮略圖。
book.volumeInfo.imageLinks && book.volumeInfo.imageLinks.thumbnail
使用打字稿
book.volumeInfo.imageLinks?.thumbnail
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.