如何在Django中实时显示amcharts数据?
我想让图表自己更新,不用刷新整个网页,就像心电监测器一样,每次数据库里有新数据时,它能自动更新,这可能吗?
用下面的代码,我必须刷新网页才能查看是否有新数据。
views.py:
from tempsensors.models import temp
def temp_page(request):
#this view is to store the temperature value into my database
#data is send by my board with a temperature sensor
if request.method == 'POST' and 'tem' in request.POST and request.POST['tem']:
temp_value = float(request.POST['tem'])
temp_add = temp(temp=temp_value)
temp_add.save()
else:
#only for post data
raise Http404
return render_to_response("temp.html",locals(),context_instance=RequestContext(request))
def chart_page(request):
#this view will display a chart
temps = temp.objects.all()
# formatting JSON file
prefix = ''
chartData = "["
for t in temps:
chartData += prefix
chartData += "{\n"
chartData += " date: "
chartData += "new Date(" + str(t.temp_date.year) + ","
chartData += str(t.temp_date.month-1) + ","
chartData += str(t.temp_date.day) + ","
chartData += str(t.temp_date.hour) + ","
chartData += str(t.temp_date.minute) + "),\n"
chartData += " value: "
chartData += str(t.temp) + "\n }"
prefix = ", "
chartData += "]"
temp_now = temp.objects.order_by("-id")[0].temp
return render_to_response('chart.html', locals())
chart.html
var chartData = {{chartData}}
chart.dataProvider = chartData;
2 个回答
0
我不能具体说Django或Amcharts,但一般来说,你可以这样做。
在你的网站页面上,你需要定期向你的服务器发送一个AJAX请求,以获取最新的完整数据集或者只是最新的数据点。这个AJAX请求可以用jQuery来实现,也可以用更基础的JavaScript。如果你拿到新的数据集(或者数据点),就更新Amchart。
还有一种更实时的方法,就是使用WebSocket,建立一个客户端和服务器之间的连接。WebSocket可以保持连接打开,这样服务器就可以直接把新的数据点推送给客户端。当然,这可能取决于你的主机是否支持WebSocket。你需要在服务器端和客户端都有合适的库来支持这个功能。