【发布时间】:2016-12-02 21:13:43
【问题描述】:
我想在单击按钮时显示随机引用。该项目在这里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>
提前谢谢你!
【问题讨论】:
标签: javascript json xmlhttprequest