I use, in my template, the following javascript to refresh an image:
<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>
And I display the image with the following html code:
<img id="imageactual" src="{{ MEDIA_URL }}{{ data_to_modify.thumbnail.name }}" />
In my view I added
@never_cache
@cache_control(max_age=0, no_cache=True, no_store=True, must_revalidate=True)
and
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
But the image is still caching in the browser (Chrome: Version 35.0.1916.153 m)... Do you have any idea how to avoid this?
EDIT 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)
As @yedpodtrzitko pointed out, adjusting the cache headers of the web page in Django is pointless.
This part looks wrong:
$.get('{{ MEDIA_URL }}{{ data_to_modify.thumbnail.name }}?cachebuster='+Math.floor(Math.random()*100 +1), function(data) {
{{ MEDIA_URL }}{{ data_to_modify.thumbnail.name }}
is the url of of the image you want to display right? (you use the same url in the html img
tag)
In that case it doesn't make sense to load that url via ajax.
It seems like you don't need ajax at all, you just need to periodically update the src
attribute of the img
tag, with the cachebuster querystring appended:
<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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.