0
我的Giphy API調用成功,但現在我試圖讓所有的圖像顯示而不是第一個。我確定在這裏需要一個循環,但我不確定如何/何時做到這一點。請參閱下面的我的HTML & jQuery代碼。在此先感謝您的時間!如何顯示所有Giphy API搜索結果圖像?
HTML
<h1>WEB 230 Final - Github Giphy API Search</h1>
<div class="outerWrapper">
<p>Please record your query in the input box, select a rating from the drop down menu, and press the search button to view results.</p>
<form>
<input type="text" id="userQuery" value="Input your query here.">
<label>
<p>Rating:</p>
<select id="rating">
<option value="" selected>all</option>
<option value="y">y</option>
<option value="g">g</option>
<option value="pg">pg</option>
<option value="pg-13">pg-13</option>
<option value="r">r</option>
</select>
</label>
<br>
<br>
<button type="submit" id="searchButton">Search</button>
<br>
<br>
<input type="reset" id="resetButton" value="Reset">
</form>
<div>
<img id="searchResults" src=""/>
</div>
</div>
JS
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
// Allows page to load prior to running jQuery code.
$(document).ready(function(){
// Ques function to run once searchButton is clicked.
$('#searchButton').on('click', function(){
// Start to construct URL that will actually be utilized in the funtion by making individual variables (some of which are dynamic) that define the search criteria.
var api = 'http://api.giphy.com/v1/gifs/search?q=';
// Assign variable for userQuery so it can be dynamically applied to the url.
var userInput = $('#userQuery').val().trim();
// Convert input for a sucessful API call.
userInput = userInput.replace(/ /g, "+");
// Set limit for maximum amount of search results displayed on one page.
var limit = '&limit=24';
/*
// Assign variable for userRating so it can be dynamically applied to the url.
var rating = $('#rating').val().trim();
// Convert input for a sucessful API call.
rating = userRnput.replace(/ /g, "+");
*/
// API public key.
var key = '&api_key=dc6zaTOxFJmzC';
// Create new variable called queryURL which pieces together all of the above variables.
var queryURL = api + userInput + key + limit /*+ rating */;
// Part 2 - Use AJAX to call GIPHY API (note that the .done() function waits for the API to respond)
$.ajax({url: queryURL, method: 'GET'}).done(function(response){
// This is the API response data. It's a JSON object of 24 gifs
console.log(response.data);
// For simplicity, we will take the first gif (ie. at postion 0)
var giphyURL = response.data[0].images.fixed_height.url;
console.log(giphyURL)
// Plug image into html.
$('#searchResults').attr('src', giphyURL);
});
// Part 3 - Clear the Gif using the reset_button id (#)
$('#resetButton').on('click', function(){
// Grab the img using the id and change the src to empty to remove the image
$('#searchResults').attr("src",'');
})
// If using a jQuery click listner on a Submit button, you need to return false to prevent the default page refresh
return false;
})
});
</script>