Javascript 谷歌图书API

Javascript 谷歌图书API,javascript,html,api,google-api,Javascript,Html,Api,Google Api,我想迭代GoogleBooksAPI提供的items数组,并在div中打印结果,但不知何故我无法这样做。这是我到现在为止写的 <body> <div class="main-body"> <form id="form"> <div class="form-group"> <label for="usr">Enter Book Name</label>

我想迭代GoogleBooksAPI提供的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>

输入图书名称
搜寻
函数function2(){
var result=document.getElementById('search-text')。值;
$.ajax({
url:“https://www.googleapis.com/books/v1/volumes?q=“+结果,
键入:“GET”,
数据类型:“json”,//添加了数据类型
成功:HandlerResponse
});
函数句柄响应(res){
$。每个(资源项目,功能(i,项目){
变量标题=item.volumeInfo.title,
author=item.volumeInfo.authors[0],
thumb=item.volumeInfo.imageLinks.thumb;
$('.title')。文本(title);
$(“.author”).text(author);
$('.thumbnail').attr('src',thumb);
})
} 
}

在每次迭代中,当前代码将用当前数据替换以前的数据。 实现您想要的最简单的方法应该是构建新元素,并将它们添加到“result”div中,如下所示

我还建议验证数据。我用没有封面或作者的返回书籍测试了一些查询

函数function2(){
var result=document.getElementById('search-text')。值;
$.ajax({
url:“https://www.googleapis.com/books/v1/volumes?q=“+结果,
键入:“GET”,
数据类型:“json”,//添加了数据类型
成功:HandlerResponse
});
函数句柄响应(res){
$。每个(资源项目,功能(i,项目){
变量标题=item.volumeInfo.title,
author=item.volumeInfo.authors[0],
thumb=item.volumeInfo.imageLinks.thumb;
var elTitle=$('').html(标题),
elAuthor=$('').html(作者),
elThumb=$('').attr('src',thumb);
$(“#结果”).append(elTitle、elAuthor、elThumb);
})
}
}

输入图书名称
搜寻

没问题。如果您认为这是解决方案,请选择它作为答案。