Django - Javascript -禁用图像刷新缓存

Django - Javascript - Disable cache on image refresh

本文关键字:刷新 缓存 图像 Javascript Django      更新时间:2023-09-26

在我的模板中,我使用以下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: Version 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中调整web页面的缓存头是没有意义的。

这部分看起来不对:

$.get('{{ MEDIA_URL }}{{ data_to_modify.thumbnail.name }}?cachebuster='+Math.floor(Math.random()*100 +1), function(data) {

{{ MEDIA_URL }}{{ data_to_modify.thumbnail.name }}是要显示的图片的url,对吗?(在html img标签中使用相同的url)

在这种情况下,通过ajax加载url是没有意义的。

看起来你根本不需要ajax,你只需要定期更新img标签的src属性,附带cachebuster查询字符串:

<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>