2016-04-27 4 views
1

ランダムクォートジェネレータWebアプリケーションを作成しています.JQueryを使用してAPIを呼び出してから、返されたJSONデータを使用して見積もりを出力できます。別の見積もりの​​ためにAPIを呼び出すためのボタンを実装しましたが、getJSON関数を呼び出しますが、新しいJSONデータは取得しません。JQuery - DivをリロードしてAPIを呼び出すとき

完全なコードはCodePenである:http://codepen.io/oscarwong67/pen/eZLQLz

は、ここで私は引用を得るために使用するものです:

<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> 

機能:

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ですページが最初に読み込まれたときに呼び出され、ボタンのクリックで呼び出されますが、返されたJSONは変更されません。

+0

問題は$ .getJSONのあなたの結果がキャッシュされていることです。 cache:falseオプションで$ .ajaxを使用するか、$ .getJSONにとどまり、$ .ajaxSetup({cache:false})を使用してください。 –

答えて

0

$ .getJSONにはキャッシュに関する問題があります。キャッシュを設定する必要があります:false。ちょうどそれを行うと、コードは正常に動作します。

キャッシュを設定するには:falseにはいくつかの方法があります。 2つの方法がある:

$(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

関連する問題