[英]How to display a newly randomly generated quote from a specific API when clicking a button?
Problem- I have an API that displays a random quote once the page loads. 问题-我有一个API,页面加载后会显示随机报价。 My button(div) called "newQuote" doesn't generate a new quote, instead, it displays the exact same quote, making my button useless.
我的名为“ newQuote”的按钮(div)不会生成新的报价,而是显示完全相同的报价,这使我的按钮无用。
My code can be found on GitHub here SO- I have a javascript function, called getNewQuote() that runs when my page loads. 我的代码可以在GitHub上找到,这里-我有一个名为getNewQuote()的JavaScript函数,该函数在页面加载时运行。 This function grabs a quote and author from an API ( https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1 ), and appends it to my div with the class quoteTitle and quoteDisplay.
此函数从API( https://quotesondesign.com/wp-json/posts?filter[ orderby]=rand&filter[posts_per_page] =1 )获取引号和作者,并将其附加到类quoteTitle和quoteDisplay的div上。 。
function getNewQuote() {
$.ajax({
url: 'https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1',
jsonp: 'jsonp',
cache: 'false',
success: function(data) {
var post = data.shift();
$("#quoteTitle").empty();
$("#quoteDisplay").empty();
$("#quoteTitle").append(post.title);
$("#quoteDisplay").append(post.content);
}
});
}
getNewQuote();
Then, I set another div called newQuote which, when clicked, would display a new quote. 然后,我设置另一个名为newQuote的div,当单击该div时将显示一个新的报价。
$('#newQuote').on('click', function(e) {
e.preventDefault();
getNewQuote();
Now, to me, it seems that the problem is caching. 现在,对我来说,问题似乎在缓存中。 The reason that I think it is a cache problem is because if I go to the site on my phone using the app Firefox Focus, which (pretty sure) doesn't store any cache, the site will run as wanted, and will change my quote whenever I click on my #newQuote.
我认为这是缓存问题的原因是,如果我使用Firefox Focus应用程序访问手机上的站点(肯定不会存储任何缓存),则该站点将按需运行,并且会更改我的站点每当我单击#newQuote时都要引用。 You can try it for yourself at 'rqg.ronlaniado.me', where it is hosted.
您可以在托管它的“ rqg.ronlaniado.me”中自行尝试。
Since my problem is cache, I did use some methods and plans to avoid this. 由于我的问题是缓存,因此我确实使用了一些方法和计划来避免这种情况。
cache: 'false',
I set cache-ing to false in my .ajax request. 我在.ajax请求中将缓存设置为false。
<script src="qg_js.js?v=42"></script>
I put "?v-42 which, according to Google, shouldn't keep cache stored. 我输入了“?v-42”,根据Google的说法,不应保留高速缓存。
If anyone can look through my code and assist me in solving my issue, that'd be great. 如果有人可以浏览我的代码并帮助我解决问题,那将是很好的。 Also, this is my first time posting here, so sorry if I am a bit messy with everything.
另外,这是我第一次在这里发布信息,对不起,如果我对所有内容都有些混乱。
The error was here: 错误在这里:
cache: 'false';
The correct usage is: 正确的用法是:
cache: false;
These quotes caused cache to be kept, meaning that the quotes didn't change. 这些引号导致保留了缓存,这意味着引号没有更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.