JQuery-重新加载Div并在点击时调用API

JQuery - Reloading a Div and Calling an API On Click

本文关键字:API 调用 Div 新加载 加载 JQuery-      更新时间:2023-09-26

我正在构建一个随机报价生成器web应用程序,我可以使用JQuery调用API,然后使用返回的JSON数据打印报价。我实现了一个按钮,试图为另一个报价调用API,它调用getJSON函数,但不会获得新的JSON数据。

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存在缓存问题。您需要设置缓存: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