javascript - 谷歌图书 API
问题描述
我想遍历 google 图书 API 提供的 items 数组并在 div 中打印结果,但不知何故我无法这样做。这是我写到现在的。
<body>
<div class="main-body">
<form id="form">
<div class="form-group">
<label for="usr">Enter Book Name</label>
<input type="search" class="form-control" id="search-text">
</div>
<div class="search-button">
<button onclick="function2();" type="button" id="search-button" class="btn btn-default">Search</button>
</div>
</form>
<div id="result">
<!--something seems wrong here-->
<h3 class="title"></h3>
<h4 class="author"></h4>
<img src="" alt="" class="thumbnail">
</div>
</div>
<script>
function function2(){
var result = document.getElementById('search-text').value;
$.ajax({
url: "https://www.googleapis.com/books/v1/volumes?q="+result,
type: 'GET',
dataType: 'json', // added data type
success: handleResponse
});
function handleResponse(res){
$.each(res.items,function(i,item){
var title = item.volumeInfo.title,
author = item.volumeInfo.authors[0],
thumb = item.volumeInfo.imageLinks.thumbnail;
<!--want to iterate over each element in items array and print it-->
$('.title').text(title);
$('.author').text(author);
$('.thumbnail').attr('src',thumb);
})
}
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
解决方案
您当前的代码在每次迭代中将先前的数据替换为当前数据。做你想做的最简单的方法应该是构建新元素并将它们附加到你的“结果”div,如下所示。
我还建议验证数据。我用没有封面或作者的退回书籍测试了一些查询。
function function2() {
var result = document.getElementById('search-text').value;
$.ajax({
url: "https://www.googleapis.com/books/v1/volumes?q=" + result,
type: 'GET',
dataType: 'json', // added data type
success: handleResponse
});
function handleResponse(res) {
$.each(res.items, function(i, item) {
var title = item.volumeInfo.title,
author = item.volumeInfo.authors[0],
thumb = item.volumeInfo.imageLinks.thumbnail;
var elTitle = $('<h3 class="title"></h3>').html(title),
elAuthor = $('<h4 class="author"></h4>').html(author),
elThumb = $('<img src="" alt="" class="thumbnail">').attr('src', thumb);
$('#result').append(elTitle, elAuthor, elThumb);
})
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="main-body">
<form id="form">
<div class="form-group">
<label for="usr">Enter Book Name</label>
<input type="search" class="form-control" id="search-text">
</div>
<div class="search-button">
<button onclick="function2();" type="button" id="search-button" class="btn btn-default">Search</button>
</div>
</form>
<div id="result">
</div>
</div>
</body>
推荐阅读
- vba - Me!control_textbox.Requery 运行时错误 '438' 对象不支持此属性或方法
- html - HTML - 由 tbody 元素建立的行组的第 2 行没有以它开头的单元格
- python - 如何修复值错误:“CB7”不在列表中?
- arrays - 如何检查直线多边形是否相交
- typo3 - 有时不会生成排版链接
- javascript - 即使凭据设置为“包含”,Cookie 也不会随 Fetch API CORS 请求一起发送
- python - 如何将变量从 python 移动到模板并返回?
- python - 有没有办法使用 python-docx 将所有项目符号列表替换为 docx 文件中的编号列表?
- javascript - 在 Laravel Inertia Vue 中初始化服务器端多列排序
- javascript - 为每个索引处存在的值过滤 javascript 多维数组