0

I would like to fetch data by clicking button.

current My work is like below code.

Are there any way to bind this?

Thanks

var apikey="https://opentdb.com/api.php?amount=1&type=multiple";

fetch(apikey)
  .then(response => response.json())
  .then(json => {
        console.log(json);
  });
<button type="button">get data</button>
Heisenberg
  • 4,787
  • 9
  • 47
  • 76

2 Answers2

0

You can add an event listener on the click of the button which uses your code:

document.getElementById('btn').addEventListener('click', function(){
     var apikey="https://opentdb.com/api.php?amount=1&type=multiple";
     fetch(apikey)
          .then(response => response.json())
          .then(json => {
               console.log(json);
          });
})
<button id="btn" type="button">get data</button>
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
0

bind on click function.

async function fetchData(){
    var apikey="https://opentdb.com/api.php?amount=1&type=multiple";

    let data =  await fetch(apikey)
      .then(response => response.json());
      
    console.log(data);
}
<button type="button" onclick="fetchData()">get data</button>
anees
  • 1,777
  • 3
  • 17
  • 26