我有一个问题。
如何调度 fetch 的事件?
在我的代码中,我添加了 addEventListener
,但我不知道为什么它不起作用。
html
<button id="btn">Button</button>
Javascript
var btn = document.getElementById('btn');
window.addEventListener('fetch', function (event) {
console.log("fetch add event listener");
});
btn.addEventListener('click', function (event) {
fetch('https://httpbin.org/get')
.then(data => {console.log(data)})
});
Codepen 链接
http://codepen.io/cnaa97/pen/JEogrr
请告诉我该怎么做。
下面是 MDN 引用链接。
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Response_objects
最佳答案
我建议你使用javascript Promise,因为它处理响应更加灵活和高效。请查看我为您创建的 jsfiddle https://jsfiddle.net/8j8uwcy7/
HTML
<button id="btn">Button</button>
JavaScript
var btn = document.getElementById('btn');
function fetch(url) {
// Return a new promise.
return new Promise(function(resolve, reject) {
console.log("fetch add event listener");
// Do the usual XHR stuff
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
// Resolve the promise with the response text3
resolve(req.response);
}
else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText));
}
};
// Handle network errors
req.onerror = function() {
reject(Error("Network Error"));
};
// Make the request
req.send();
});
}
btn.addEventListener('click', function (event) {
fetch('https://httpbin.org/get').then(function(response) {
console.log("Success!", response);
}, function(error) {
console.error("Failed!", error);
})
});
打开浏览器控制台并查看响应。您现在可以从 API 中提取必要的数据。
关于Javascript 获取事件处理程序不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41500982/