点击调用Fetch



我设置了一个获取请求,该请求从API请求一个随机短语。这是在窗口重新加载或初始加载时调用的。我创建了一个按钮,点击后会重新运行我设置的获取。目前它不工作,我得到这个错误:

Uncaught(in promise(TypeError:在未实现接口Window的对象上调用了"fetch"。

Javascript代码

var generateBtn = document.getElementById('generateSP');
generateBtn.addEventListener('click', fetch);
fetch('https://random-words-api.herokuapp.com/w?n=10')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
response.json().then(function(data) {
console.log(data);
document.getElementById('w3review').value = data;
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});

只需用一个函数包装您的代码。你不能这样叫fetch。

var generateBtn = document.getElementById('generateSP');
generateBtn.addEventListener('click', fetchData);
function fetchData() {
fetch('https://random-words-api.herokuapp.com/w?n=10')
.then(function (response) {
if (response.status !== 200) {
console.log(
'Looks like there was a problem. Status Code: ' + response.status
);
return;
}
response.json().then(function (data) {
console.log(data);
document.getElementById('w3review').value = data;
});
})
.catch(function (err) {
console.log('Fetch Error :-S', err);
});
}

您需要将fetch调用封装在自定义回调中,它不能用作addEventListener:的参数

var generateBtn = document.getElementById('generateSP');
generateBtn.addEventListener('click', myFetcher);
function myFetcher() {
fetch('https://random-words-api.herokuapp.com/w?n=10')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
response.json().then(function(data) {
console.log(data);
document.getElementById('w3review').value = data;
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
})
}
myFetcher();

您的原始代码在点击时调用fetch((,没有url或参数传入。

不要将点击处理程序直接绑定到fetch,这根本不起作用。创建自己的调用fetch()的函数,并将侦听器绑定到该

const loader = async () => {
try {
const res = await fetch('https://random-words-api.herokuapp.com/w?n=10')
if (!res.ok) {
throw new Error(`${response.status}: ${await response.text()}`)
}
const data = await response.json()
console.log(data);
document.getElementById('w3review').value = data;
} catch (err) {
console.error(err)
}
}
document.getElementById('generateSP').addEventListener('click', loader);
loader() // initial run

要详细说明错误消息,必须调用绑定到window对象的fetch。任何事件侦听器都绑定到触发事件的元素,所以这就像试图调用一样

const boundFetch = window.fetch.bind(generateBtn)
boundFetch(event)

这会导致您的错误。

最新更新