【问题标题】:Django - Javascript - Disable cache on image refreshDjango - Javascript - 在图像刷新时禁用缓存
【发布时间】:2014-06-18 08:28:32
【问题描述】:

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

【问题讨论】:

  • 这些响应标头仅与网页相关,与图像无关。该图像由另一个请求提供,并且该响应具有自己的标头。我认为您需要修改给定目录/文件类型的网络服务器设置。

标签: javascript ajax django image browser-cache


【解决方案1】:

正如@yedpodtrzitko 指出的那样,在Django 中调整网页的缓存头是没有意义的。

这部分看起来不对:

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

【讨论】:

  • 如果您打算每 2 秒刷新一次,您可能应该使用比 100 大得多的数字来清除缓存。
  • @itsadok ...好点,这部分是从 OP 复制和粘贴的,但我看不出有任何理由不直接使用 Math.random() 并仅从js区间
  • @Anentropic 您的回答正在解决我的问题,但旧图像仍保留在浏览器缓存中。
  • @Erwan 来控制缓存行为,您需要更改任何提供图像文件的服务返回的标头,即您的网络服务器 - Apache、Nginx 或其他任何东西
猜你喜欢
  • 2018-02-14
  • 1970-01-01
  • 2015-06-20
  • 2012-08-02
  • 2013-02-15
  • 1970-01-01
  • 2012-10-12
  • 1970-01-01
  • 2017-05-31
相关资源
最近更新 更多