首页 > 解决方案 > 当我搜索 Giphy API 时,搜索字段变为空

问题描述

我一直在使用 Giphy API,试图让我的 Giphy 应用程序正常工作。每当我向 Giphy API 发送搜索时,我的搜索就会变成空的。即使我在搜索字段中输入了一些内容。我console.log()什么都有,控制台告诉我我的搜索参数是空的。不知道为什么我在搜索字段中执行的任何内容都没有发送到 API。这是一些 Javascript 代码: ``let giphySend = $("#giphySend"); let giphyInput = $("#giphyInput") .val() .trim(); let giphyHeader = $("#giphyHeader h1"); let giphyAPIKey = "GET A GIPHY API KEY"; let giphyInputArray = []; $(giphySend).on("click", function() { event.preventDefault(); let url = "https://api.giphy.com/v1/gifs/search?api_key=" + giphyAPIKey + "&limit=5&q=" + giphyInput; ``fetch(url) .then(response => { console.log(response); return response.json(); }) .then(json => { console.log(json); console.log(json.data); })

     .catch(err => console.log(err));
 });

抱歉,格式有点奇怪。这是一些 HTML:

  `<aside id="aside">
      <input
        type="search"
        placeholder="Search Giphy..."
        id="giphyInput"
      /><input type="submit" value="Send Request" id="giphySend" />
    </aside>
    <script src="assets/javascript/app.js"></script>`

标签: javascriptjqueryhtml

解决方案


问题是您let giphyInput = $("#giphyInput").val().trim();在单击事件之外定义,因此当您运行单击事件时giphyInput为空,因为在实时运行时输入为空。

解决方案:

$(giphySend).on("click", function() {
let giphyInput = $("#giphyInput").val().trim();

将输入移动到单击事件中。


推荐阅读