【问题标题】:Stop image from caching in jQuery停止在 jQuery 中缓存图像
【发布时间】:2017-04-30 12:54:31
【问题描述】:

我正在尝试在 FreeCodeCamp 上完成随机报价生成器。我几乎拥有它,但我决定我想更进一步并使用按钮更改背景图像。我相信背景 img 是从最初设置背景 img 的第一次调用中缓存的。因此,每次我点击按钮时,浏览器实际上是在重新加载缓存的 img,而不是重新访问网站并拉取新的 img。

我使用的来源只是一个网站,每次访问都会返回不同的图像。

我尝试在网址末尾添加时间戳,但网站只是向我抛出了无效的地址图像。

<html>
  <head>
  </head>
  <body>
    <div class="container-fluid" id="mainDiv">
     <div class = "row text-center">
      <div class = "col-xs-12 well" id = "quote">
      The quote will go here
      </div>
    </div>
    <div class = "row text-center">
      <div class = "col-xs-12">
        <button id = "getQuote" class = "btn btn-primary">
        Get Quote
        </button>
      </div>
    </div>
  </div>
  </body>
</html> 

body{
  background-image: ;
}
#mainDiv{
  margin: 0 auto;
  max-width: 400px;
  margin-top: 200px;
}

$(document).ready(function(){
  $('body').css('background-image', 'url("https://source.unsplash.com/random")');
  $.getJSON("http://quotes.stormconsultancy.co.uk/random.json", function(json){
    $("#quote").html('"' +json.quote + '"<br> - ' + json.author);
  });
  $("#getQuote").on("click", function(){
    $('body').css('background-image', 'url("https://source.unsplash.com/random")');
    $.getJSON("http://quotes.stormconsultancy.co.uk/random.json", function(json){
      $("#quote").html('"' +json.quote + '"<br> - ' + json.author);
    });
  });
});

【问题讨论】:

    标签: javascript jquery html css caching


    【解决方案1】:

    时间戳不起作用,因为它是 302 重定向,并且客户端脚本无法拦截 302 重定向,它会自动解析,您对此无能为力。不过,您可以在服务器端读取 302 标头。您可以尝试在服务器中获取图像,让它解析 302 并以正确的 url 响应。

    如果您正在使用 API,您可以尝试使用 ajax:

    $.ajax({
      url: "https://api.unsplash.com/photos/random?client_id=32d223323",
      cache: false,
      success: function(result){
         $('body').css('background-image', 'url("' + result.urls.full + '")');
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-08
      • 2014-04-06
      • 2018-08-03
      • 2021-11-28
      • 1970-01-01
      • 2019-03-12
      • 1970-01-01
      相关资源
      最近更新 更多