我正在使用 Google Books API 来显示简单图书搜索的结果。但是,在执行搜索时,某些项目会重复返回。参见:图书搜索
要获取此数据并以 HTML 格式显示,我这样做:
var result = document.getElementById("result");
var cover, title, author, book_id;
function handleResponse(response) {
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
// Create elements
figure = document.createElement("figure");
aEmp = document.createElement("a");
aId = document.createElement("a");
img = document.createElement("img");
figcap = document.createElement("figcaption");
// Get data from JSON
try {
cover = item.volumeInfo.imageLinks.thumbnail;
title = item.volumeInfo.title;
author = item.volumeInfo.authors;
book_id = item.id;
} catch (error) {
continue;
} finally {
// Set value to elements e send to HTML
result.appendChild(figure);
aEmp.appendChild(img);
aId.innerHTML = "ADICIONAR";
aId.href = `/add/${book_id}`;
aId.classList.add("dropdown");
figure.appendChild(aId);
figure.appendChild(aEmp);
img.src = cover;
figcap.innerHTML += `${title}<br>${author}`;
figure.appendChild(figcap);
}
}
}
document.querySelector("form").addEventListener("submit", function (e) {
result.innerHTML = "";
search = document.getElementById("search").value;
var script = document.createElement("script");
script.src = `https://www.googleapis.com/books/v1/volumes?q=${search}&callback=handleResponse`;
document.body.appendChild(script);
e.preventDefault();
});
这是我上传的图片上使用的 JSON 示例:
https://www.googleapis.com/books/v1/volumes?q=$harry+potter&callback=handleResponse