javascript - 从 API onclick 加载数据

标签 javascript fetch-api

我正在尝试制作简单的应用程序。我想在屏幕上显示引号,并且我正在使用 API 来获取它们。我正在使用 fetch 来获取 API 数据。

现在,窗口加载时一切正常,但我想让按钮在每次有人单击该按钮时获取新报价,但我无法让它工作。

这是我的原始代码:

fetch('https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=', {
  cache: "no-cache"
})
  .then(response => response.json())
  .then(function(data) {
    console.log(data);
  
    data.filter(key => {
      
      let quote = document.getElementById('quote');
      let author = document.getElementById('author');
      
      quote.innerHTML = key.content;
      author.innerHTML = key.title;
      
    });

  })
  .catch(function(error) {
    // If there is any error you will catch them here
    console.log(error);
  });

为了使报价在点击时加载,我尝试了以下操作:

const newQuote = document.getElementById('newQuote')
 newQuote.addEventListener('click', _ => {
   fetch('https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=', {
    mode: 'no-cors'
   })
    .then(response => response.json())
    .then(data => {
      data.filter(key => {
          let quote = document.getElementById('quote')
          quote.innerHTML = key.content
      })
    })
    .catch(err => console.error(err))
 })

那么我可以让它与点击事件一起工作吗?这是 JSBin,以便您可以更好地理解我的问题:

https://jsbin.com/qidudat/edit?html,js,output

最佳答案

我改变了解决问题的方法。问题之一是我使用了 no-cors 模式。

以下是任何感兴趣的人的解决方案:

function getQuote() {
  fetch("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=" + Math.random())
    .then(response => response.json())
    .then(function(data) {
      console.log(data);

      data.filter(key => {

        let quote = document.querySelector(".quote");
        let author = document.querySelector(".author");
        let cleanQuote = key.content.replace(/<\/?p[^>]*>/g, ''); // This way we remove <p> tag from quote (api has quotes with p tags)

        let share = 'https://twitter.com/home?status=' + cleanQuote + ' Author: ' + key.title;
        console.log(share)

        quote.innerHTML = key.content;
        author.innerHTML = key.title;
        
        document.getElementById('twitterShare').href=share;
      });

    })
    .catch(function(error) {
      // If there is any error you will catch them here
      console.log(error);
    });
}

const newQuote = document.getElementById('newQuote')
newQuote.addEventListener('click', getQuote); // new quote on button click
window.onload = getQuote; // new quote on page load

关于javascript - 从 API onclick 加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45353852/

相关文章:

javascript - javascript 动态内容对于脚本小子来说是否足够安全?

javascript - 设置 fetch API 调用的延迟

javascript - Ajax 从 jquery 到 javascript

javascript - 获得 promise 值(value)

javascript - 全局调用异步函数时出错 : "await is only valid in async functions and the top level bodies of modules"?

android - React-native/AWS API Gateway 安卓问题

javascript - 如何使用悬停菜单界面填充 textInput spacer

javascript - react : Dynamically setting element keys

javascript - 使用 2x 类通过 jQuery 选择和切换第三个

javascript - 删除最后一次出现的字符串