$.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](https://i.stack.imgur.com/KT9mH.png)
См. В этом примере:
$(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>
Надеюсь, это поможет!