javascript - 我的获取请求被取消了,我不知道为什么
问题描述
我正在创建一个使用https://restcountries.eu/ API 的 Web 应用程序。
当用户键入国家/地区时,我将使用fetch
. 但是,我的请求总是被取消。
我测试了捕获用户输入的部分,但我认为问题出在我的fetch
代码上。
var countryName; // This will receive the user input on a textbox in my HTML file.
var resultado;
function grabCountry(urlendpoint, countryName, endpointfields) {
countryName = document.getElementById('searchInput').value;
var urlendpoint = 'https://restcountries.eu/rest/v2/name/';
var endpointfields = '?fields=topLevelDomain;alpha3Code;callingCodes;altSpellings;subregion;population;latlng;languages;flag';
fetch(urlendpoint + countryName + endpointfields)
.then(response => data)
.then(data => {
console.log(data())
})
}
解决方案
取消调用的原因之一fetch
可能是触发事件的 HTML 标记是 HTML 表单标记的子(或孙)标记。在这种情况下,该事件可能会触发将开始提交表单数据的表单,因此它自然会取消您的fetch
呼叫。
解决方案之一是preventDefault
在触发fetch
调用的事件上调用函数。请参见下面的示例:
function myFetchFunction(event) {
event.preventDefault();
fetch("https://my-url-here");
}
<button onclick="myFetchFunction">Fetch</button>
推荐阅读
- java - 应用程序在测试设备上调试时工作正常,但在发布 apk 中没有,它没有从 firebase 获取 post.class 变量
- javascript - 解析页面时通过另一个脚本调用 JavaScript PostBack
- php - 在codeigniter登录后无法将用户的所有数据保留在会话中
- javascript - 使用 redux 道具更新的 useEffect
- oracle - plsql 过程不是过程或未定义
- perl - Perl - 需要一遍又一遍地调用 system('diff')
- php - 如何使用 PHP 在浏览器控制台上打印
- python - 我正在尝试编写一个“机器人”服务员程序,但我似乎找不到哪里出错了
- java - JavaFX:使 LocalDateTime 触发事件?
- constraint-programming - 如何将两个元素放在同一个序列中?