好的,我需要创建一个搜索表单来从男高音API中检索GIF ...(Json)...在这种情况下我知道如何检索它们......
问题
我需要集成实时搜索输入(或基本形式以开始)...例如,如果我写aa
,它会查找以aa
开头的GIF。问题出在这一行var search_term = document.getElementById("search_text").value;
JAVASCRIPT / JSON
function tenorCallback_search(responsetext)
{
// parse the json response
var response_objects = JSON.parse(responsetext);
top_10_gifs = response_objects["results"];
// load the GIFs -- for our example we will load the first GIFs preview size (nanogif) and share size (tinygif)
// document.getElementById("preview_gif").src = top_10_gifs[0]["media"][0]["nanogif"]["url"];
// document.getElementById("share_gif").src = top_10_gifs[0]["media"][0]["tinygif"]["url"];
response_objects.results.forEach((gifObj, i) => {
img_gif_created= document.createElement('img');
img_gif_created.setAttribute("id", "gif_"+i)
// do something with each gifObj
document.querySelector('.container')
.appendChild(img_gif_created)
.src = gifObj.media[0].nanogif.url;
});
return;
}
// function to call the trending and category endpoints
function grab_data(anon_id)
{
// set the apikey and limit
var apikey = "***************";
var lmt =50;
// test search term
var search_term = document.getElementById("search_text").value;
// using default locale of en_US
var search_url = "https://api.tenor.com/v1/search?tag=" + search_term + "&key=" +
apikey + "&limit=" + lmt + "&anon_id=" + anon_id;
httpGetAsync(search_url,tenorCallback_search);
// data will be loaded by each call's callback
return;
}
HTML
<form method="GET" action="">
<input type=text id="search_text" >
<input type=submit>
</form>
<div class="container"></div>
答案 0 :(得分:1)
我会将一个事件处理程序附加到侦听更改事件的输入字段。然后,您需要过滤图像数组,并将项目与输入值进行比较。以下是概念的快速证明。您需要重构此操作并添加检查不匹配的条件。
ES6:
const images = ['aa908.gif', 'aa745.gif', 'foo26.gif', 'bar222.gif'];
const input = document.getElementById('search_text');
let searchTextVal = '';
input.addEventListener('input', function () {
searchTextVal = this.value.toLowerCase();
let startsWith = images.filter((image) => image.startsWith(searchTextVal));
console.log(startsWith);
});
ES5:
'use strict';
var images = ['aa908.gif', 'aa745.gif', 'foo26.gif', 'bar222.gif'];
var input = document.getElementById('search_text');
var searchTextVal = '';
input.addEventListener('input', function () {
searchTextVal = this.value.toLowerCase();
var startsWith = images.filter(function (image) {
return image.startsWith(searchTextVal);
});
console.log(startsWith);
});