您如何使用jquery和AJAX从JSON文件中获取图像并将其显示在我的页面上?这是我的代码。
function bookSearch(){
var search = document.getElementById('search').value;
//Results innerHTML is an empty string, so it would be a new search each time.
document.getElementById('results').innerHTML= ""
$.ajax ({
url: "https://www.googleapis.com/books/v1/volumes?q=" + search,
dataType: "json",
success: function(data){
var results= document.getElementById('results');
for(i = 0; i < data.items.length; i++){
results.innerHTML += "<span class='col-md-4'>" + data.items[i].volumeInfo.title + "</span>"
results.innerHTML += "<img class='col-md-4'>" + data.items[i].imageLinks.smallThumbnail + "</img>"
}
},
type: 'GET'
});
}
document.getElementById('button').addEventListener('click', bookSearch, false)
答案 0 :(得分:5)
您需要设置图片HTML元素的src
属性。
results.innerHTML += "<img class='col-md-4' src='" + data.items[i].volumeInfo.imageLinks.smallThumbnail + "'"
以下是代码的工作实现。另外,请注意我使用jquery操作DOM。
$(document).ready(function()
函数,以便在DOM完全加载时注册事件处理程序。 $('#search').val();
方法。$('#results').html('')
方法设置innerHTML。on
方法$("#button").on("click", bookSearch);
smallThumbnail
属性应以data.items[i].volumeInfo.imageLinks.smallThumbnail
而不是data.items[i].imageLinks.smallThumbnail
$(document).ready(function(){
function bookSearch(){
var search = $('#search').val();
//Results innerHTML is an empty string, so it would be a new search each time.
document.getElementById('results').innerHTML= ""
$.ajax ({
url: "https://www.googleapis.com/books/v1/volumes?q=" + search,
dataType: "json",
success: function(data){
var innerHTML = "";
for(var i=0; i < data.items.length; i++){
if(data.items[i].volumeInfo.title && data.items[i].volumeInfo.imageLinks &&
data.items[i].volumeInfo.imageLinks.smallThumbnail){
innerHTML += "<span class='col-md-4' title='>" + data.items[i].volumeInfo.title + "'</span>" +
"<img class='col-md-4' src='" + data.items[i].volumeInfo.imageLinks.smallThumbnail + "'>";
}
}
$('#results').html(innerHTML);
},
type: 'GET'
});
}
$("#button").on("click", bookSearch);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="search" type="text"/>
<button id="button">image</button>
<div id="results"></div>
答案 1 :(得分:2)
我相信你是在正确的轨道上。然而,&#39; img&#39;标签要求您指定&#39; src&#39;显示图像。
我认为这就是你要找的东西:
for(i = 0; i < data.items.length; i++){
results.innerHTML += "<span class='col-md-4'>" + data.items[i].volumeInfo.title + "</span>"
results.innerHTML += "<img class='col-md-4' src='" + data.items[i].imageLinks.smallThumbnail + "'/>"
}