最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Load data from API onclick - Stack Overflow

programmeradmin2浏览0评论

I'm trying to make simple app. I want to show quotes on screen and I'm using API to get them. I'm using fetch to get API data.

Now everything works fine when window loads but I wanted to make button to get new quote each time someone clicks on that button and I can't get it to work.

This is my original code:

fetch('[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);
  });

To make quotes load on click I have tried following:

const newQuote = document.getElementById('newQuote')
 newQuote.addEventListener('click', _ => {
   fetch('[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))
 })

So can I make it work with click event? Here is JSBin so you can better understand my problem:

,js,output

I'm trying to make simple app. I want to show quotes on screen and I'm using API to get them. I'm using fetch to get API data.

Now everything works fine when window loads but I wanted to make button to get new quote each time someone clicks on that button and I can't get it to work.

This is my original code:

fetch('https://quotesondesign./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);
  });

To make quotes load on click I have tried following:

const newQuote = document.getElementById('newQuote')
 newQuote.addEventListener('click', _ => {
   fetch('https://quotesondesign./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))
 })

So can I make it work with click event? Here is JSBin so you can better understand my problem:

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

Share Improve this question edited Nov 10, 2023 at 17:09 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jul 27, 2017 at 14:33 Zvezdas1989Zvezdas1989 1,4652 gold badges20 silver badges34 bronze badges 12
  • perhaps write your callback without the fat arrow, you may be losing the scope of this – HolyMoly Commented Jul 27, 2017 at 14:37
  • @HolyMoly Tried it didn't work. – Zvezdas1989 Commented Jul 27, 2017 at 14:46
  • 1 okay, so lets debug...when you console.log the API response, do you see the quotes? Have you verified that your HTML element is being correctly captured by the document.getElementById('newQuote')? why do you have the leading // prior to the API's url, rather than http:// or something? have you console.log'd data? – HolyMoly Commented Jul 27, 2017 at 14:50
  • are you getting any errors in console? – HolyMoly Commented Jul 27, 2017 at 14:53
  • @HolyMoly Yeah you can check JSBin again and paste the first snippet of code into JS you will see data load. When I console.log api response I get json with data you can also see that if you use my first snippet. I've "//" used because I've thought CORS could be the problem. – Zvezdas1989 Commented Jul 27, 2017 at 14:59
 |  Show 7 more ments

2 Answers 2

Reset to default 2

I've changed my approach to the problem. One of the issues was that I used no-cors mode.

Here is the solution for anyone interested:

function getQuote() {
  fetch("https://quotesondesign./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./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

Turn off caching when you use the fetch API call in your new code as well.... I think that should do it.

发布评论

评论列表(0)

  1. 暂无评论