我有一个问题。
如何发送fetch事件?
在我的代码中,我添加了addEventListener
,但我不知道它为什么不起作用。
<button id="btn">Button</button>
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)})
});
http://codepen.io/cnaa97/pen/JEogrr
请告诉我该怎么做。
以下是MDN参考链接
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Response_objects
答案 0 :(得分:0)
我建议你使用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中提取必要的数据。