首页 > 解决方案 > 如何使用 Giphy API 编写用于搜索的 gif 网格?

问题描述

我有几个问题...

我有一个用于搜索栏的 HTML 表单,我试图将其发送到 Giphy API,但是当我addEventListener("click")为提交按钮编写代码时,我无法获取用户在输入标签上输入的字符串。

HTML:

<form id="input_bar"> <input type="text" name="search_string" id="search_string"> <button type="submit" id="search_submit">Submit!</button> </form>

JS:

const searchBar = document.getElementById("search_string"); const submitBtn = document.getElementById("search_submit");

submitBtn.addEventListener("click", function getResults(submitBtn) { var searchResult = fetch("https://api.giphy.com/v1/gifs/search?q=" + submitBtn + "&api_key=" + apiKey) .then(function(response) { console.log(response); }) });

发送的获取 URL 是

{...}/search?q= [object%20M...seEvent] &api_key={...}

我错过了什么?

另外,我不知道如何将 附加response.json到 a<div id="results_grid"></div>以返回 gif 网格。

谢谢你的帮助!

标签: javascripthtml

解决方案


您将按钮对象而不是搜索栏值发送到 API。

改变这个:

searchResult = fetch("https://api.giphy.com/v1/gifs/search?q=" + submitBtn + "&api_key=" + apiKey) .then(function(response) { console.log(response); }) });

对此:

searchResult = fetch("https://api.giphy.com/v1/gifs/search?q=" + searchBar.value + "&api_key=" + apiKey) .then(function(response) { console.log(response); }) });

推荐阅读