我正在尝试制作简单的应用程序。我想在屏幕上显示引号,并且我正在使用 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,以便您可以更好地理解我的问题:
最佳答案
我改变了解决问题的方法。问题之一是我使用了 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/