我一直在使用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>`发布于 2019-10-18 14:07:32
问题是您在单击事件之外定义了let giphyInput = $("#giphyInput").val().trim();,所以当您运行单击事件时,giphyInput为null,因为在实时运行时,输入为null。
解决方案:
$(giphySend).on("click", function() {
let giphyInput = $("#giphyInput").val().trim();将输入移动到单击事件中。
发布于 2019-10-18 14:12:27
你正在做的错误是,当你的脚本或网页加载时,你从搜索框中获取了值,所以最初giphyInput = "";而当你点击搜索按钮时,它仍然是一个空字符串。你必须告诉从DOM获取最新的值。
所以在你的on("click")回调函数中这样做。
$(giphySend).on("click", function() {
`event.preventDefault();`
`//tell jquery to give latest value`giphyInput = $("#giphyInput").val().trim()
`//Rest of your code with fetch function`}
https://stackoverflow.com/questions/58444639
复制相似问题