简体   繁体   English

停止在jQuery中缓存图像

[英]Stop image from caching in jQuery

I am trying to complete the random quote generator on FreeCodeCamp. 我正在尝试在FreeCodeCamp上完成随机报价生成器。 I pretty much have it but i decided i wanted to go one step further and change the background image with the button as well. 我几乎拥有它,但我决定我想更进一步,并使用按钮更改背景图像。 I believe the background img is being cached from the very first call where the background img is originally set. 我相信背景img是从最初设置背景img的第一个调用中缓存的。 Therefor every time i click the button the browser is essentially reloading the cached img instead of revisiting the site and pulling a new img. 因此,每次我单击按钮时,浏览器实际上是在重新加载缓存的img,而不是重新访问该站点并提取新的img。

The source i am using is just a site that returns a different image every visit. 我使用的来源只是一个网站,每次访问都会返回不同的图像。

I have tried adding a time stamp to the end of the url and the site just throws a invalid address image at me. 我尝试在网址末尾添加时间戳,但该网站向我抛出了无效的地址图像。

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

Timestamp won't work because it is a 302 redirect, and the client-side script cannot intercept the 302 redirect, it is resolved automatically and you cannot do anything about that. 时间戳无法使用,因为它是302重定向,并且客户端脚本无法拦截302重定向,它会自动解决,因此您无法执行任何操作。 You can read 302 headers on the server side though. 不过,您可以在服务器端读取302标头。 You can try getting the image in your server, have it resolve the 302 and respond with the correct url. 您可以尝试在服务器中获取图像,让它解析302并使用正确的URL进行响应。

If you are using the API you can try using ajax: 如果您使用的是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 + '")');
  }
});

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

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