gpt4 book ai didi

javascript - 点击时随机报价(API + JavaScript)

转载 作者:行者123 更新时间:2023-11-30 15:40:11 24 4
gpt4 key购买 nike

我想在单击按钮时显示随机引用。项目在这里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>

提前致谢!

最佳答案

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

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

关于javascript - 点击时随机报价(API + JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40932875/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com