1
我正在構建一個隨機引用生成器Web應用程序,我可以使用JQuery調用API,然後使用返回的JSON數據打印出報價。我已經實現了一個按鈕來嘗試調用另一個報價的API,其中調用了getJSON函數,但未獲取新的JSON數據。JQuery - 重新加載Div並調用API點擊
完整的代碼是CodePen:http://codepen.io/oscarwong67/pen/eZLQLz
下面是我用得到的報價:
var getQuote = function() {
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1" + "?callback?", function(json) {
console.log(json);
$("#quote").html(json[0].content);
$("#speaker").html("- " + json[0].title);
});
}
getQuote(); //called when the page initially loads
$("#new-quote").on("click", function() {
getQuote();
});
下面是相關的HTML,它改變:
<div class="col-xs-12 col-sm-8 col-md-6 text-center" id="quote-div">
<p id="quote">Loading Your Quote</p>
<p id="speaker"></p>
<button class="btn btn-default btn-block" id="new-quote">New Quote!</button>
</div>
功能在頁面最初加載時調用,並會調用按鈕單擊,但返回的JSON不會更改。
的問題是,你的$ .getJSON的結果被緩存。將$ .ajax與cache:false選項一起使用,或者使用$ .getJSON並使用$ .ajaxSetup({cache:false}) –