2010-09-21 18 views
2

我正在監視不同位置的溫度。我將數據存儲在模型中並設置了我的views.py,但我想每5分鐘刷新一次表格。我是新來的ajax和dajaxice,我怎麼能寫的功能,使其顯示在HTML?這是我的views.py:用Django中的Dajaxice刷新表格

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}) 

至於什麼我想我瞭解,到目前爲止,這可能是我的ajax.py,我應該只是修改它返回一個simplejson轉儲。如果我錯了,請糾正我。這是我的temp.html:

<table id="tval"><tr> 
{% for label, value in temperature.items %} 
     <td>{{ label }}</td> 
     <td>{{ value }}</td> 
{% endfor %} 
    </tr></table> 

這裏是我卡住的地方。我怎麼寫這個以便我的回調刷新表格?

回答

6

使用類似的話是這樣的:

from django.template.loader import render_to_string 
from django.utils import simplejson 
from dajaxice.core import dajaxice_functions 

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 
    table = render_to_string('temp.html', {'temperature': temperature_dict}) 
    return simplejson.dumps({'table':table}) 

dajaxice_functions.register(temperature) 

而作爲JS回調,分配 '表' 到你的HTML容器......(這只是一個例子):

function my_callback(data){ 
    if(data!=Dajaxice.EXCEPTION){ 
     document.getElementById('your_table_container_id').innerHTML = data.table; 
    } 
    else{ 
     alert('Error'); 
    } 
} 

希望這有助於您。

+0

這真的很有幫助。謝謝! – dura 2010-09-21 19:15:17