我创建了一个简单的页面,显示来自QuotesOnDesign API的随机引号。但是,单击"New“元素不会触发getQuote函数。下面是我的代码的链接:
CodePen随机引号
我怀疑这与jQuery有关,因为console显示了一个错误,提到它拒绝加载脚本(指jQuery)。奇怪的是,当我在Chrome中打开开发工具时,点击"New“,它就能工作了!
发布于 2015-07-15 20:48:39
浏览器在第一次调用API时缓存响应,并在以后的调用中重用该响应。您可以通过向URL添加cachebuster来解决此问题。
当您打开控制台时,它工作的原因是您可能拥有禁用缓存(而DevTools是打开的)选项集。
function getQuote() {
var cb = Math.round(new Date().getTime() / 1000);
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=" + cb, function(a) {
$(".quote-text").html(a[0].content + "<p>— " + a[0].title + "</p>");
});
}工作CodePen
发布于 2015-07-15 20:48:51
您可以完全摆脱函数式调用,并让$.ajax尝试如下:
$(".button").on("click", function(e) {
e.preventDefault();
$.ajax({
url: 'http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1',
success: function(a) {
$(".quote-text").html(a[0].content + "<p>— " + a[0].title + "</p>")
},
cache: false
});
});使用cache: false,您将在每次调用的基础上防止缓存,因此每次按下按钮时,内容都会按预期进行更改。
https://stackoverflow.com/questions/31440314
复制相似问题