我正在创建一个使用 https://restcountries.eu/ 的 Web 应用程序API。
当用户输入国家/地区时,我将使用 fetch
向 API 发出请求.但是,我的请求总是被取消。
我测试了捕获用户输入的部分,但我认为问题出在我的 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 Form 标记的子(或孙)。在这种情况下,该事件可能会触发将开始提交表单数据的表单,因此它自然会取消您的fetch
。称呼。
解决方案之一是调用 preventDefault
触发 fetch
的事件的函数称呼。请参见下面的示例:
function myFetchFunction(event) {
event.preventDefault();
fetch("https://my-url-here");
}
<button onclick="myFetchFunction">Fetch</button>
关于javascript - 我的获取请求被取消了,我不知道为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64619140/