我已經設定了一個從 API 請求隨機短語的獲取請求。這在視窗重新加載或最初加載時呼叫。我創建了一個按鈕,當點擊它時會重新運行我設定的提取。目前它不起作用,我收到此錯誤:
Uncaught (in promise) TypeError: 'fetch' 在未實作介面 Window 的物件上呼叫。
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);
});
uj5u.com熱心網友回復:
只需用一個函式包裝你的代碼。你不能像這樣呼叫 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);
});
}
uj5u.com熱心網友回復:
您需要將 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 或引數。
uj5u.com熱心網友回復:
不要將點擊處理程式直接系結到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
要詳細說明錯誤資訊,fetch 必須呼叫系結到window物件。任何事件偵聽器都系結到觸發事件的元素,因此就像嘗試呼叫
const boundFetch = window.fetch.bind(generateBtn)
boundFetch(event)
這會導致您的錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/388129.html
標籤:javascript 获取-api
