简体   繁体   English

Javascript获取事件处理程序不起作用

[英]Javascript fetch event handler doesn't work

I have a question. 我有个问题。

How can I do dispatch fetch's event? 我如何发送fetch的事件?

In my code, I added addEventListener , but I don't know why It doesn't work. 在我的代码中,我添加了addEventListener ,但我不知道为什么它不起作用。

html HTML

<button id="btn">Button</button>

Javascript 使用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 Link Codepen链接

http://codepen.io/cnaa97/pen/JEogrr http://codepen.io/cnaa97/pen/JEogrr

Please advise me what to do. 请告诉我该怎么做。

Below is the MDN reference link. 以下是MDN参考链接。

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Response_objects https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Response_objects

I suggest you to use javascript Promise as it is more flexible and efficient to handle response. 我建议你使用javascript Promise,因为它更灵活,更有效地处理响应。 Please look at the jsfiddle i have created for you https://jsfiddle.net/8j8uwcy7/ 请看看我为你创建的jsfiddle https://jsfiddle.net/8j8uwcy7/

HTML HTML

<button id="btn">Button</button>

JavaScript 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);
     })   
});

Open the browser console and see the response. 打开浏览器控制台并查看响应。 You can now extract the necessary data from the API. 您现在可以从API中提取必要的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM