从api onclick加载数据

时间:2017-07-27 14:33:11

标签: javascript api fetch

我正在尝试制作简单的应用。我想在屏幕上显示引号,我正在使用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))
 })

所以我可以让它与click事件一起工作吗?这是JSBin所以你可以更好地理解我的问题: https://jsbin.com/qidudat/edit?html,js,output

2 个答案:

答案 0 :(得分:2)

我已经改变了,我可以解决这个问题。其中一个问题是使用了无人模式。

这是任何有兴趣的人的解决方案:

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

答案 1 :(得分:0)

在新代码中使用fetch API调用时关闭缓存....我认为应该这样做。