2016-12-15 109 views
0

我想完成FreeCodeCamp上的随机引用生成器。我几乎拥有它,但我决定我想更进一步,并使用按钮更改背景图像。我相信背景img是从最初设置背景img的第一个电话缓存的。因此,每次我点击按钮浏览器基本上重新加载缓存的img,而不是重新访问该网站,并拉动新的img。从jQuery缓存中停止图像

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

我已经尝试添加一个时间戳到URL的结尾,该网站只是在我身上抛出一个无效的地址图像。

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

回答

0

时间戳不会起作用,因为它是一个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 + '")'); 
    } 
});