我使用下面的代码和一个搜索字段(输入)从Pixabay返回结果。不管我在搜索中使用什么关键字,我总是得到相同的5个结果(见附图)。我遗漏了什么?任何帮助都非常感谢!
var API_KEY = 'my_hidden_api_key',
searchTerm,
submitSearch = $('#cms_pixaSearchBtn'),
boxPixaResults = $('#cms_displayPixaResults'),
URL = "https://pixabay.com/api/?key="+API_KEY+"&safesearch=true&q="+encodeURIComponent(searchTerm);
submitSearch.click(function(){
searchTerm = $('#cms_pixaSearchKeywords').val();
console.log(searchTerm);
$.getJSON(URL, function(data){
if (parseInt(data.totalHits) > 0)
$.each(data.hits, function(i, hit){
console.log(hit.pageURL);
boxPixaResults.append('<img src="' + hit.previewURL + '" alt="">');
});
else
console.log('No hits');
});
}); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input id="cms_pixaSearchKeywords" type="text" value="">
<input id="cms_pixaSearchBtn" type="button" value="search">
<div id="cms_displayPixaResults"></div>

发布于 2019-09-05 22:06:05
URL = "https://pixabay.com/api/?key="+API_KEY+"&safesearch=true&q="+encodeURIComponent(searchTerm);在调用click处理程序之前定义:
submitSearch.click(function(){
searchTerm = $('#cms_pixaSearchKeywords').val();所以searchTerm是空的。
根据documentation,如果q为空,您将获得所有图像。
要修复,请执行以下操作:
submitSearch.click(function(){
searchTerm = $('#cms_pixaSearchKeywords').val();
URL = "https://pixabay.com/api/?key="+API_KEY+"&safesearch=true&q="+encodeURIComponent(searchTerm);https://stackoverflow.com/questions/57806671
复制相似问题