我想遍历google book 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>
答案 0 :(得分:1)
您的当前代码在每次迭代时都将当前数据替换为当前数据。 进行所需操作的最简单方法应该是构建新元素,并将它们append插入“结果” 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>