2016-04-27 33 views
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不會更改。

+0

的問題是,你的$ .getJSON的結果被緩存。將$ .ajax與cache:false選項一起使用,或者使用$ .getJSON並使用$ .ajaxSetup({cache:false}) –

回答

0

$ .getJSON在高速緩存方面存在問題。您需要設置緩存:false。只要做到這一點,你的代碼工作正常。

要設置緩存:false有許多方法。兩種可能的方法是:

$(document).ready(function() { 
    $.ajaxSetup({ cache: false }); 
}); 

$.ajaxSetup({ cache: true}); 
$.getJSON("/url",function(data,item) { 
    // do stuff with callback data 
    $.ajaxSetup({ cache: false}); 
    }); 

你最後的JS:

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); 
    $("#speaker").css('text-align', "right"); 
    $("#speaker").css('padding-right', "2%"); 
    $("#speaker").css('font-size', "16pt"); 
    $("#speaker").css('font-weight', "bold"); 
    $.ajaxSetup({ cache: false }); 
    }); 
} 

Codepen