我正在尝试在 FreeCodeCamp 上完成随机报价生成器。我几乎拥有它,但我决定我想更进一步并使用按钮更改背景图像。我相信背景 img 是从最初设置背景 img 的第一次调用中缓存的。因此,每次我单击该按钮时,浏览器实际上是在重新加载缓存的 img,而不是重新访问该站点并提取新的 img。
我使用的来源只是一个网站,每次访问都会返回不同的图像。
我已经尝试在 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);
});
});
});
最佳答案
Timestamp 将不起作用,因为它是 302 重定向,客户端脚本无法拦截 302 重定向,它会自动解析,您对此无能为力。不过,您可以在服务器端读取 302 header 。您可以尝试在您的服务器中获取图像,让它解析 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 + '")');
}
});
关于javascript - 停止在 jQuery 中缓存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41155385/