dur*_*ura 5 django jquery django-views
我想在Django中刷新包含温度数据的div标签.每20秒获取一次数据.到目前为止,我已使用以下功能实现了这一目
function refresh() {
$.ajax({
url: '{% url monitor-test %}',
success: function(data) {
$('#test').html(data);
}
});
};
$(function(){
refresh();
var int = setInterval("refresh()", 10000);
});
Run Code Online (Sandbox Code Playgroud)
这是我的urls.py:
urlpatterns += patterns('toolbox.monitor.views',
url(r'^monitor-test/$', 'temperature', name="monitor-test"),
url(r'^monitor/$', 'test', name="monitor"),
)
Run Code Online (Sandbox Code Playgroud)
views.py:
def temperature(request):
temperature_dict = {}
for 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})
Run Code Online (Sandbox Code Playgroud)
temp.html有一个include标记:
<table id="test"><tbody>
<tr>
{% include "testing.html" %}
</tr>
</tbody></table>
Run Code Online (Sandbox Code Playgroud)
testing.html只包含一个for标签来遍历字典:
{% for label, value in temperature.items %}
<td >{{ label }}</td>
<td>{{ value }}</td>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
div每10秒刷新一次,允许我使用模板系统而不用js修补它.但是,我在几分钟后同时反复拨打'/ monitor-test',3-4.另外,我想知道是否有更好的方法来实现这一点,同时能够在Django中使用模板系统.谢谢.
我通常解决这种情况的3-4"并发"请求的方法是将setTimeout()调用放在我想要重复运行的函数中.
function refresh() {
$.ajax({
url: '{% url monitor-test %}',
success: function(data) {
$('#test').html(data);
}
});
setTimeout(refresh, 10000);
}
$(function(){
refresh();
});
Run Code Online (Sandbox Code Playgroud)
这样就可以在每次refresh调用函数时自动将其自身设置为在10秒内再次调用.另一个想法(如果你还有问题)是setTimeout在AJAX调用中移入成功函数:
function refresh() {
$.ajax({
url: '{% url monitor-test %}',
success: function(data) {
$('#test').html(data);
}
setTimeout(refresh, 10000);
});
}
$(function(){
refresh();
});
Run Code Online (Sandbox Code Playgroud)
如果由于某种原因,AJAX调用不成功,那么该选项可能会有点粗略.但是你总是可以和其他处理程序一起解决这个问题,我想......
我有一个建议(与您的问题没有特别相关)是将整个<table>内容放在您呈现的模板中并返回您的temperature视图.所以,在你的主模板中:
<div id="test">
{% include 'testing.html' %}
</div>
Run Code Online (Sandbox Code Playgroud)
并在testing.html:
<table><tr>
{% for label, value in temperature.items %}
<td>{{ label }}</td>
<td>{{ value }}</td>
{% endfor %}
</tr></table>
Run Code Online (Sandbox Code Playgroud)
关于以你当前的方式插入表的一部分的事情让我想哭:)在AJAX调用中通过线路发送几个字节应该不会伤害任何东西.
| 归档时间: |
|
| 查看次数: |
7744 次 |
| 最近记录: |