【问题标题】:JavaScript: How to "refresh" data from same URL?JavaScript:如何“刷新”来自同一 URL 的数据?
【发布时间】:2017-08-08 00:03:55
【问题描述】:

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

如何使用纯 JS 请求在按钮单击事件后下载不同的数据?

我从这段代码中得到的始终是相同的报价:

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);
    });
})

我尝试了 xmlhttp.abort() 之类的东西,但它不想合作。 提前致谢!

【问题讨论】:

  • 你会用jQuery吗?
  • 我不想要。我的意思是,没关系,它会工作的。但我的目标是正确学习纯 JS。我上次制作了工作“应用程序”,但不知道它为什么工作。
  • 啊好吧... jQuery 中有缓存控制。

标签: javascript xmlhttprequest


【解决方案1】:

浏览器正在缓存您的响应。避免这种情况的一个常见技巧是向

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

注意 r={random_number} 将如何使 URL 每次都不同。

【讨论】:

    【解决方案2】:

    这是一个缓存问题。添加时间戳作为查询参数,您应该能够破坏缓存。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2012-12-23
      • 2011-09-22
      相关资源
      最近更新 更多