如何在单击按钮时从 API 获取数据 - Javascript?

How to fetch data from API on button click - Javascript?

我有这部分代码:

fetch(`https/someapi.com/data`)
            .then(response => {
                return response.json()
            }).then(randomProduct => {
                document.querySelector('#list').innerHTML = `
                <span>${randomProduct.value}</span>
                <button id="refresh-button" type="button">Refresh</button>
                `;
                
                var clickOnButton = document.querySelector("#refresh-button");
                clickOnButton.addEventListener("click", () => {


 })
            })

如何让这个 onClick 事件刷新我从 API 读取的数据并显示一个新数据?

我不确定我是否正确理解了您的问题,但据我所知,您只想编辑获取时的数据,无需每次都创建按钮和侦听器。将提取放在一个专用函数中,该函数称为提取中按钮的 onClick,只需编辑值即可。

你可以把它全部包装在一个函数中,然后像这样调用它

const fakeApi = () => new Promise(resolve => setTimeout(() => resolve({
  value: Math.floor(Math.random() * 100)
}), 500))

const getData = () => fakeApi().then(randomProduct => {
  document.querySelector('#main').innerHTML = `
                <span>${randomProduct.value}</span>
                <button id="refresh-button" type="button" onclick="getData()">Refresh</button>`

})

getData()
<div id="main"></div>

首先你需要一个按钮来发出获取请求

const fetchDataBtn = document.querySelector('#fetchdata')
const result = document.querySelector('#result')

// gets data from API and sets the content of #result div
const getData = function() {
  result.innerText = 'Loading....'
  fetch('https://dummyjson.com/products')
    .then(res => res.json())
    .then(data => {
      result.innerText = JSON.stringify(data, null, 2)
    })
    .catch(error => console.log(error))
}

// add event listener for #fetchdata button
fetchDataBtn.addEventListener('click', getData)

const fetchDataBtn = document.querySelector('#fetchdata')
    const result = document.querySelector('#result')
    
    // gets data from API and sets the content of #result div
    const getData = function() {
      result.innerText = 'Loading....'
      fetch('https://dummyjson.com/products')
        .then(res => res.json())
        .then(data => {
          result.innerText = JSON.stringify(data, null, 2)
        })
        .catch(error => console.log(error))
    }
    
    // add event listener for #fetchdata button
    fetchDataBtn.addEventListener('click', getData)
<button id="fetchdata">FETCH</button>
<div id="result"></div>