点击随机引用(API + JavaScript)

时间:2016-12-02 13:01:29

标签: javascript json xmlhttprequest

我想在点击按钮时显示随机引用。该项目在https://skidle.github.io/projects/random-quote。如果打开控制台,可以看到此onclick=newQuote()函数正在运行,因为它会在控制台中生成JSON对象。但引用保持不变,我应该以某种方式更改URL吗?

JS:

var xhr = new XMLHttpRequest();
xhr.open("GET", "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1");
xhr.send();

xhr.onreadystatechange = function () {
    var DONE = 4; // readyState 4 means the request is done.
    var OK = 200; // status 200 is a successful return.
    if (xhr.readyState === DONE) {
      if (xhr.status === OK) {
        var json = JSON.parse(xhr.responseText);
        var elQuote = document.getElementById("quote");
        elQuote.innerHTML = json[0]["content"];
        var elAuthor = document.getElementById("author");
        elAuthor.innerHTML = json[0]["title"];
        console.log(json[0]);
      } else {
        console.log("Error: " + xhr.status); // An error occurred during the request.
      }
    };
  }

var newQuote = function() {
//the script below is the same as above just inserted inside newQuote()
  var xhr = new XMLHttpRequest();
xhr.open("GET", "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1");
xhr.send();
  xhr.onreadystatechange = function () {
    var DONE = 4; // readyState 4 means the request is done.
    var OK = 200; // status 200 is a successful return.
    if (xhr.readyState === DONE) {
      if (xhr.status === OK) {
        var json = JSON.parse(xhr.responseText);
        var elQuote = document.getElementById("quote");
        elQuote.innerHTML = json[0]["content"];
        var elAuthor = document.getElementById("author");
        elAuthor.innerHTML = json[0]["title"];
        console.log(json[0]);
      } else {
        console.log("Error: " + xhr.status); // An error occurred during the request.
      }
    };
  }
}

HTML:

<main>
      <div class="container">
        <div class="wrapper">
          <section id="quote">
          </section>
          <div class="button-wrapper">
            <button>Tweet this</button>
            <div id="author"></div>
            <button onclick="newQuote()">New quote</button>
          </div>
        </div>
      </div>
 </main>

提前谢谢!

1 个答案:

答案 0 :(得分:2)

我认为ajax请求正在缓存。尝试在网址中添加时间戳,如下所示:

    xhr.open("GET", "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&timestamp="+new Date());