简体   繁体   English

JavaScript:如何从相同的网址“刷新”数据?

[英]JavaScript: How to “refresh” data from same URL?

Having this API: http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1 拥有此API: http : //quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1

How can I write using pure JS request that downloads me different data after button click event? 如何在单击事件后使用纯JS请求编写可下载不同数据的纯JS请求?

All I get from this code is the same quote all the time: 我从这段代码中得到的一直都是相同的引用:

function getQuote (cb) {
 var xmlhttp = new XMLHttpRequest();
 var quoteURL = "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand"
 xmlhttp.onreadystatechange = function() {
    if (xmlhttp.status == 200 && this.readyState==4) {
        cb(this.responseText);
    } 
};
    xmlhttp.open("GET", quoteURL, true);
    xmlhttp.send();
}

document.querySelector('button').addEventListener("click", function() {
    getQuote(function(quote) {
        console.log(quote);
    });
})

I tried xmlhttp.abort() and stuff but it didnt want to cooperate. 我尝试了xmlhttp.abort()和其他东西,但它不想合作。 Thanks in advance! 提前致谢!

This is a caching problem. 这是一个缓存问题。 Add a timestamp as a query parameter and you should be able to bust the cache. 添加时间戳记作为查询参数,您应该可以破坏缓存。

Your response is being cached by the browser. 您的回复正在被浏览器缓存。 A common trick to avoid this is to perform a request to 避免这种情况的常见技巧是执行请求

http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&r={random_number}

Notice how the r={random_number} will make the URL different each time. 请注意,r = {random_number}每次都会使URL不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用javascript中的刷新功能发送数据并使用相同的刷新功能检索其他数据 - How do I send data using a refresh function in javascript and retrieve another data using the same refresh function 刷新时如何将相同的参数添加到 Url - How To Add The Same Parameters To The Url When Refresh 如何从 javascript 中的 url 中获取 json 数据? - How to get json data from url in javascript? 如何使用 JavaScript 从 URL 读取数据? - How to read data from URL using JavaScript? 如何在 JavaScript 中从数组中分离相同的数据 - How to separate same data from array in JavaScript 如何在不刷新的情况下更改innerHTML或使用JavaScript中的相同按钮进行刷新和输出 - How to change innerHTML without refresh or refresh and output with same button in javascript 如何不从JavaScript刷新页面? - How not to refresh a page from JavaScript? 如何从JavaScript中的URL获取具有相同名称的多个参数 - How to get multiple parameters with same name from a URL in JavaScript 如何在不刷新页面的情况下使用 JavaScript 从 window.location (URL) 中删除散列? - How to remove the hash from window.location (URL) with JavaScript without page refresh? 错误:数据源必须是 URL 才能刷新 | 控制台错误 | javascript | Highcharts - Error: Data source must be a URL for refresh | console error | javascript | Highcharts
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM