我在我的模板中使用以下 javascript 来刷新图像:
<script type='text/javascript'>
$(document).ready(function() {
var $img = $('#imageactual');
setInterval(function() {
$.get('{{ MEDIA_URL }}{{ data_to_modify.thumbnail.name }}?cachebuster='+Math.floor(Math.random()*100 +1), function(data) {
var $loader = $(document.createElement('img'));
$loader.one('load', function() {
$img.attr('src', $loader.attr('src'));
});
$loader.attr('src', data);
if($loader.complete) {
$loader.trigger('load');
}
});
}, 2000);
});
</script>
然后我使用以下 html 代码显示图像:
<img id="imageactual" src="{{ MEDIA_URL }}{{ data_to_modify.thumbnail.name }}" />
在我看来我添加了
@never_cache
@cache_control(max_age=0, no_cache=True, no_store=True, must_revalidate=True)
和
response = render(request, 'mainsite/modify.html', locals(), context_instance=RequestContext(request))
response['Cache-Control'] = 'no-store, no-cache, must-revalidate proxy-revalidate'
response['Expires'] = 'Thu, 01 Jan 1970 00:00:00 GMT'
response['Pragma'] = 'no-cache'
return response
但图像仍在浏览器中缓存(Chrome:版本 35.0.1916.153 m)...您知道如何避免这种情况吗?
编辑 1:
**Header:**
Remote Address:127.0.0.1:80
Request URL:http://127.0.0.1/medias/thumbs/odbgelguelteeglndjssastj.jpg
Request Method:GET
Status Code:200 OK (from cache)
最佳答案
正如@yedpodtrzitko 指出的那样,在 Django 中调整网页的缓存 header 毫无意义。
这部分看起来不对:
$.get('{{ MEDIA_URL }}{{ data_to_modify.thumbnail.name }}?cachebuster='+Math.floor(Math.random()*100 +1), function(data) {
{{ MEDIA_URL }}{{ data_to_modify.thumbnail.name }}
是您要显示的图片的网址吗? (你在 html img
标签中使用相同的 url)
在这种情况下,通过 ajax 加载该 url 是没有意义的。
看起来你根本不需要 ajax,你只需要定期更新 img
标签的 src
属性,附加 cachebuster querystring:
<script type='text/javascript'>
$(document).ready(function() {
var $img = $('#imageactual');
setInterval(function() {
$img.attr('src', '{{ MEDIA_URL }}{{ data_to_modify.thumbnail.name }}?cachebuster='+Math.floor(Math.random()*100 +1));
}, 2000);
});
</script>
关于javascript - Django - Javascript - 在图像刷新时禁用缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24280655/