javascript - 当我搜索 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>`
解决方案
问题是您let giphyInput = $("#giphyInput").val().trim();
在单击事件之外定义,因此当您运行单击事件时giphyInput
为空,因为在实时运行时输入为空。
解决方案:
$(giphySend).on("click", function() {
let giphyInput = $("#giphyInput").val().trim();
将输入移动到单击事件中。
推荐阅读
- python - Groupby 一个 Pandas DataFrame 并单独绘制组
- java - 类编译但在运行时不可用:Robot() 显示 java.lang.reflect.InvocationTargetException
- javascript - glTF 文件没有显示任何内容
- apache-spark - 如何在不重复的情况下分组 - Apache Pig
- python - 使用 DistilBERT 生成文本句子
- asynchronous - 基于异步事件管理订阅
- arrays - 如何在一个 mongodb 集合中获取一个值并使用该值更新另一个集合订单和库存系统中的另一个文档
- c++ - GetDIBits 在屏幕捕获函数中多次迭代后返回零
- sql - 带分组依据的 SQL 语句 - 乘客列表
- android - 带有两个(或更多)图像的平滑滑块