我试图在搜索后显示通过API调用拉出的多个GIF。当我只想显示一个gif但我想要迭代JSON文件并显示多个gif时,我能够使代码工作。
我试图使用$ .each,但每当我这样做时,我会得到一些未定义的相关错误。我已尝试过在JSON数组中调用数据的各种组合,但仍无法使其工作。
var data = [{"date":1468195200000,"row":0}]
var rw = data[0].row;
var dt = new Date(data[0].date);
console.log(rw);
console.log(dt);

$(document).ready(function(){
$('#gif-search-button').click(function (evt){
evt.preventDefault();
var url ='http://api.giphy.com/v1/gifs/search?api_key=dc6zaTOxFJmzC';
var gifRequest = 'q=' + $('#gif-search').val();
gifCallback = function (data) {
var returnedgif = '<div>';
$.each(data, function(index, gif){
returnedgif += '<a href="' + gif.data.url + '">';
returnedgif += '<img id="resultGif" src="' + gif.data.images.fixed_height.url + '"></a>';
console.log(returnedgif)
})
returnedgif += '</div>'
$('#resultGif').html(returnedgif);
} //End of callback function
$.getJSON(url, gifRequest, gifCallback);
}); //End of click event
});
&#13;
答案 0 :(得分:1)
在迭代中执行以下操作:
$.each(data.data, function(index, gif){
问题在于响应来自以下结构
数据
GIF1
...
gifN
因此,在您的代码中,您应该迭代data.data
,因为第一个data
是从作为getJSON
参数提供的gifCallback
返回的变量,第二个是API返回的内容。
$(document).ready(function(){
$('#gif-search-button').click(function (evt){
evt.preventDefault();
var url ='http://api.giphy.com/v1/gifs/search?api_key=dc6zaTOxFJmzC';
var gifRequest = 'q=' + $('#gif-search').val();
gifCallback = function (data) {
var returnedgif = '<div>';
$.each(data.data, function(index, gif){
returnedgif += '<a href="' + gif.url + '">';
returnedgif += '<img id="resultGif" src="' + gif.images.fixed_height.url + '"></a>';
console.log(returnedgif)
})
returnedgif += '</div>'
$('#resultGif').html(returnedgif);
} //End of callback function
$.getJSON(url, gifRequest, gifCallback);
}); //End of click event
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<form class='form-group search-form'>
<div class="grid">
<div class="row">
<div class="col-sm-4" >
<label for="gif-search" class='lead'>What type of gif are you looking for?</label>
<input type="text" id="gif-search" class="form-control" placeholder='dancing bears' />
</div>
</div>
<div class="row">
<button type="submit" class='btn btn-danger search-form' id="gif-search-button">Find that gif</button>
</div>
</div>
</form>
<div id="resultGif">
</div>
</div>