简体   繁体   中英

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

How can I write using pure JS request that downloads me different data after button click event?

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM