我正在尝试在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);
});
});
});
答案 0 :(得分: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 + '")');
}
});