Refresh div using JQuery in Django while using the template system -
i want refresh in django contains temperature data. data fetched every 20 seconds. far have achieved using these functions:
function refresh() { $.ajax({ url: '{% url monitor-test %}', success: function(data) { $('#test').html(data); } }); }; $(function(){ refresh(); var int = setinterval("refresh()", 10000); });
and urls.py:
urlpatterns += patterns('toolbox.monitor.views', url(r'^monitor-test/$', 'temperature', name="monitor-test"), url(r'^monitor/$', 'test', name="monitor"), )
views.py:
def temperature(request): temperature_dict = {} filter_device in temperaturedevices.objects.all(): get_objects = temperaturedata.objects.filter(device=filter_device) current_object = get_objects.latest('date') current_data = current_object.data temperature_dict[filter_device] = current_data return render_to_response('temp.html', {'temperature': temperature_dict})
temp.html has include tag:
<table id="test"><tbody> <tr> {% include "testing.html" %} </tr> </tbody></table>
testing.html contains tag iterate through dictionary:
{% label, value in temperature.items %} <td >{{ label }}</td> <td>{{ value }}</td> {% endfor %}
the div refreshed every 10 seconds , allows me use template system without patching js. however, repeated calls '/monitor-test', 3-4 @ same time after couple of minutes. also, wondering if there better way while being able use template system in django.
the way around 3-4 "concurrent" requests such situations put settimeout()
call inside function want run repeatedly.
function refresh() { $.ajax({ url: '{% url monitor-test %}', success: function(data) { $('#test').html(data); } }); settimeout(refresh, 10000); } $(function(){ refresh(); });
that makes every time refresh
function called, automatically set called again in 10 seconds. idea (if still have problems) move settimeout
success function in ajax call:
function refresh() { $.ajax({ url: '{% url monitor-test %}', success: function(data) { $('#test').html(data); } settimeout(refresh, 10000); }); } $(function(){ refresh(); });
that option might little bit sketchy if, whatever reason, ajax call not succeed. can around other handlers, suppose...
one suggestion have (not particularly related question) putting whole <table>
thing in template render , return temperature
view. so, in main template:
<div id="test"> {% include 'testing.html' %} </div>
and in testing.html
:
<table><tr> {% label, value in temperature.items %} <td>{{ label }}</td> <td>{{ value }}</td> {% endfor %} </tr></table>
something inserting part of table way have makes me want cry :) sending few more bytes on wire in ajax calls shouldn't hurt anything.
Comments
Post a Comment