Google books jquery автозаполнение из api url call json не работает - PullRequest
1 голос
/ 09 февраля 2020

У меня есть окно поиска, findBook, и я пытаюсь использовать автозаполнение jquery с помощью json api для вызова google-books api для отображения названия книги, автора и эскиза.

Когда я печатаю в поле поиска, ничего не происходит. Любая помощь будет оценена. Источником для автозаполнения является URL-адрес Google-Boosk API. Спасибо:)

<!DOCTYPE html>
<html>
<head>

<!-- Your web-app is https, so your scripts need to be too -->


<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" href="/style.css" type="text/css">
<link rel="stylesheet" href="/home.css" type="text/css">

<script src='https://code.jquery.com/jquery-2.2.4.js'
        integrity="sha256-gvQgAFzTH6trSrAWoH1iPo9Xc96QxSZ3feW6kem+O00="
        crossorigin="anonymous"></script>

<script src='https://code.jquery.com/ui/1.12.0/jquery-ui.js'></script>
<link href="https://code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css" rel="stylesheet" media="screen" />
<script type='text/javascript'>

</script>

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js'></script>

<script type="text/javascript">
    $(document).ready(function(){

        $("#findBook").autocomplete({
            source: function (request, response) {

                $.ajax({
                    method:"GET",
                    dataType: "json",
                    url: "https://www.googleapis.com/books/v1/volumes?q=" + request.term,


                    success: function (data) {
                        console.log(data);
                        var transformed = $.map(data.items.volumeInfo, function (book) {
                            return {
                                title: book.title,
                                author: book.author,
                                image: book.imageLinks.thumbnail
                            };
                        });

                        response(transformed);
                    },

                    error: function () {

                        response([]);
                    }
                });
            }

        });
    });

 </script>


</head>
<body>


 <div class="searchBook">



   <input type="text" placeholder="Search.." id="findBook" />


</div>



  </body>

</html>

Ответы [ 2 ]

1 голос
/ 09 февраля 2020

$.map() jQuery функция требует массив для итерации. В вашем случае: data.items.volumeInfo - это undefined.

Однако вы можете использовать функцию Array#map JavaScript для перебора по data.items, таким образом:

var transformed = data.items.map(function(book) {
  return {
    title: book.volumeInfo.title,
    author: book.volumeInfo.authors,
    image: book.volumeInfo.imageLinks.thumbnail
  };
});

В приведенном выше коде объект книги имеет атрибут volumeInfo, поэтому вы можете получить доступ к его атрибутам для создания нового объекта, в данном случае transformed переменная.

Теперь, чтобы показать название книги, автора и миниатюру, вам нужно будет изменить обработанный плагин HTML из jQuery автозаполнения, используя функцию _renderItem.

Что-то вроде этой функции :

.autocomplete("instance")._renderItem = function(ul, item) {
  return $("<li></li>")
    .data("item.autocomplete", item)
    .append("<a>" + "<img src=\"" + item.image + "\" style=\"height: 40%;\" /><br />" + (item.author && item.author.length ? item.author.map(function(x) {
      return x;
    }).join(" | ") : '') + " - " + item.title + "</a>")
    .appendTo(ul);
};

Получение этого результата:

enter image description here

См. В этом примере:

$(function() {

  $("#findBook").autocomplete({
    source: function(request, response) {
      $.ajax({
        url: "https://www.googleapis.com/books/v1/volumes?q=" + request.term,
        dataType: "json",
        data: {
          term: request.term
        },
        success: function(data) {
          var transformed = data.items.map(function(book) {
            return {
              title: book.volumeInfo.title,
              author: book.volumeInfo.authors,
              image: book.volumeInfo.imageLinks.thumbnail
            };
          });
          response(transformed);
        }
      });
    }
  }).autocomplete("instance")._renderItem = function(ul, item) {
    return $("<li></li>")
      .data("item.autocomplete", item)
      .append("<a>" + "<img src=\"" + item.image + "\" style=\"height: 40%;\" /><br />" + (item.author && item.author.length ? item.author.map(function(x) {
        return x;
      }).join(" | ") : '') + " - " + item.title + "</a>")
      .appendTo(ul);
  };
});
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Remote JSONP datasource</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>

<body>
  <div class="searchBook">
    <input type="text" placeholder="Search..." id="findBook">
  </div>
</body>

</html>

Не забудьте не смешивать разные версии библиотеки jQuery.

Обновление: Показывать только изображение .

Параметры отображаются по умолчанию, , если в них есть текст для отображения . Тем не менее, мы можем добавить скрытый span с текстом, где он будет только показывать изображение.

Что-то похожее в этом примере:

$(function() {

  $("#findBook").autocomplete({
    source: function(request, response) {
      $.ajax({
        url: "https://www.googleapis.com/books/v1/volumes?q=" + request.term,
        dataType: "json",
        data: {
          term: request.term
        },
        success: function(data) {
          var transformed = data.items.map(function(book) {
            return {
              title: book.volumeInfo.title,
              author: book.volumeInfo.authors,
              image: book.volumeInfo.imageLinks.thumbnail
            };
          });
          response(transformed);
        }
      });
    }
  }).autocomplete("instance")._renderItem = function(ul, item) {
    return $("<li></li>")
      .data("item.autocomplete", item)
      .append("<img src=\"" + item.image + "\" style=\"height: 40%;\" /><span hidden>" + item.image + "</span>")
      .appendTo(ul);
  };
});
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Remote JSONP datasource</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>

<body>
  <div class="searchBook">
    <input type="text" placeholder="Search..." id="findBook">
  </div>
</body>

</html>

Надеюсь, это поможет!

0 голосов
/ 09 февраля 2020

Вы загружаете две версии jQuery версии jquery-2.2.4 и jquery/3.3.1/jquery.js и версию 3, которая загружается после jquery UI. Вот в чем проблема.

I Просто удалите jquery-2x и переместите jquery3x перед jquery UI. На самом деле должно работать, если вы просто переместите jquery-3x до jquery-UI без удаления чего-либо.

<!DOCTYPE html>
<html>
<head>
<!-- Your web-app is https, so your scripts need to be too -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" href="/style.css" type="text/css">
<link rel="stylesheet" href="/home.css" type="text/css">
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js'></script>
<script src='https://code.jquery.com/ui/1.12.0/jquery-ui.js'></script>
<link href="https://code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css" rel="stylesheet" media="screen" />
<script type="text/javascript">
    $(document).ready(function(){

        $("#findBook").autocomplete({
            source: function (request, response) {

                $.ajax({
                    method:"GET",
                    dataType: "json",
                    url: "https://www.googleapis.com/books/v1/volumes?q=" + request.term,


                    success: function (data) {
                        console.log(data);
                        var transformed = $.map(data.items.volumeInfo, function (book) {
                            return {
                                title: book.title,
                                author: book.author,
                                image: book.imageLinks.thumbnail
                            };
                        });

                        response(transformed);
                    },

                    error: function () {

                        response([]);
                    }
                });
            }

        });
    });
</script>
</head>
<body>
    <div class="searchBook">
        <input type="text" placeholder="Search.." id="findBook" />
    </div>
</body>
</html>

example here

...