javascript - Django - Javascript - 在图像刷新时禁用缓存

标签 javascript ajax django image browser-cache

我在我的模板中使用以下 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/

相关文章:

python - Django Python 垃圾收集问题

javascript - 如何从 Backbone.listenTo 中查找触发事件?

php - 分离 Web 应用程序各部分的经验法则

php - 为什么 PJAX 会阻止 Nestable 工作?

javascript - d'n'd 如何通过 Ajax 传输文件(或文件夹)?

jquery - $(document).on ('click' ... $.ajax 调用仅执行一次

python - Django:如何在应用程序中组织静态页面?

python - Django 没有在 Windows 机器上正确安装

javascript - 如何在打印中设置页边距顶部、底部?

javascript - else if javascript 中的语句无法显示验证消息