每5秒更新一次Django模板失败

时间:2015-09-21 15:35:21

标签: ajax django setinterval

我正在构建一个Django项目并尝试使用AJAX。我需要刷新我的模板,每隔5秒就会从Raspberri Pi中获取新数据。数据存储在SQLite数据库中。

我是Django的新手,也是Ajax的新手。我尝试从基本的东西开始,这是我的代码:

view.py

from django.http import HttpResponse
from django.template import RequestContext,loader
from .models import Results

def index(request):
    return HttpResponse(loader.get_template('mysensor/index.html').render(RequestContext(request,{'latest_results_list':Results.objects.all()})))


def update(request):
     return HttpResponse(loader.get_template('mysensor/index.html').render(RequestContext(request,{'latest_results_list':Results.objects.all()})))

我的模板:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
 <script type="text/javascript">


    $( document ).ready(function() {
       setInterval(function(){
           $.ajax({
               url:'/mysensor/update' ,
               type: "get",
               cache: true,
               timeout: 30000,
               dataType: 'html',
               success: function(data) {
                   console.log("success");
                   $('#MyTable').html(data);
               },
               error: function(data) {
                   alert("Got an error dude "+data);
               }
           });
       },5000);
    });

 </script>

<table id="MyTable">
<tr>
  <th>Date</th>
  <th>Time</th>
  <th>Temperature</th>
 <th>Humidity</th>
</tr>
{% for b in latest_results_list %}
<tr>
  <td>{{ b.date }}</td>
  <td>{{ b.time }}</td>
  <td>{{ b.temperature }}</td>
<td>{{ b.humidity }}</td>
</tr>
{% endfor %}
</table>

在运行时,我的网页崩溃并分析服务器日志,表格不会像我预期的那样每5秒刷新一次,但它会崩溃。

服务器日志片段:

[21/Sep/2015 10:43:46] "GET /mysensor/ HTTP/1.1" 200 7517
[21/Sep/2015 10:43:51] "GET /mysensor/update HTTP/1.1" 301 0
[21/Sep/2015 10:43:51] "GET /mysensor/update/ HTTP/1.1" 200 7517
[21/Sep/2015 10:43:56] "GET /mysensor/update/ HTTP/1.1" 200 7517
[21/Sep/2015 10:43:56] "GET /mysensor/update/ HTTP/1.1" 200 7517
[21/Sep/2015 10:44:01] "GET /mysensor/update/ HTTP/1.1" 200 7517
[21/Sep/2015 10:44:01] "GET /mysensor/update/ HTTP/1.1" 200 7517
[21/Sep/2015 10:44:01] "GET /mysensor/update/ HTTP/1.1" 200 7517
[21/Sep/2015 10:44:01] "GET /mysensor/update/ HTTP/1.1" 200 7517
[21/Sep/2015 10:44:06] "GET /mysensor/update/ HTTP/1.1" 200 7517
[21/Sep/2015 10:44:06] "GET /mysensor/update/ HTTP/1.1" 200 7517
[21/Sep/2015 10:44:06] "GET /mysensor/update/ HTTP/1.1" 200 7517
[21/Sep/2015 10:44:06] "GET /mysensor/update/ HTTP/1.1" 200 7517
[21/Sep/2015 10:44:06] "GET /mysensor/update/ HTTP/1.1" 200 7517
[21/Sep/2015 10:44:06] "GET /mysensor/update/ HTTP/1.1" 200 7517
[21/Sep/2015 10:44:06] "GET /mysensor/update/ HTTP/1.1" 200 7517
[21/Sep/2015 10:44:07] "GET /mysensor/update/ HTTP/1.1" 200 7517
[21/Sep/2015 10:44:11] "GET /mysensor/update/ HTTP/1.1" 200 7517
[21/Sep/2015 10:44:11] "GET /mysensor/update/ HTTP/1.1" 200 7517
[21/Sep/2015 10:44:11] "GET /mysensor/update/ HTTP/1.1" 200 7517
[21/Sep/2015 10:44:11] "GET /mysensor/update/ HTTP/1.1" 200 7517
[21/Sep/2015 10:44:11] "GET /mysensor/update/ HTTP/1.1" 200 7517
[21/Sep/2015 10:44:11] "GET /mysensor/update/ HTTP/1.1" 200 7517
[21/Sep/2015 10:44:11] "GET /mysensor/update/ HTTP/1.1" 200 7517

任何建议都将不胜感激。 提前谢谢。

3 个答案:

答案 0 :(得分:2)

这对我有用:

views.py:

from django.http import HttpResponse
from django.template import RequestContext,loader
from .models import Results

from django.http import JsonResponse

def index(request):
    return HttpResponse(loader.get_template('mysensor/index.html').render(RequestContext(request,{'latest_results_list':Results.objects.all()})))

def update(request):
     results = [ob.as_json() for ob in Results.objects.all()]
     return JsonResponse({'latest_results_list':results})

模板:

<script type="text/javascript" src="{{STATIC_URL}}jquery-1.11.3.min.js"> </script>

<script type="text/javascript">   
    $( document ).ready(function() {
       setInterval(function(){
            $.getJSON('/mysensor/update',
                    function (data) {
                        var json = data['latest_results_list'];
                        var tr;
                         $('#myTable tbody').html("");
                        for (var i = 0; i < json.length; i++) {
                            tr = $('<tr/>');
                            tr.append("<td>" + json[i].date + "</td>");
                            tr.append("<td>" + json[i].time + "</td>");
                            tr.append("<td>" + json[i].temperature + "</td>");
                            tr.append("<td>" + json[i].humidity + "</td>");
                             $('#myTable tbody').append(tr);

                        }
                    });
       },5000);
    });

</script>

<table id ='myTable'>
    <thead>
    <tr>
      <th>Date</th>
      <th>Time</th>
      <th>Temperature</th>
      <th>Humidity</th>
    </tr>
    </thead>
    <tbody >
         {% for b in latest_results_list %}
             <tr>
             <td>{{ b.fecha }}</td>
             <td>{{ b.tiempo }}</td>
             <td>{{ b.temperatura }}</td>
             <td>{{ b.humedad }}</td>
             </tr>                 
         {% endfor %}
    </tbody >        
</table>

这些答案帮助我找到了解决方案:

答案 1 :(得分:1)

您只想更新表,但ajax请求返回的data将包含整个html,包括脚本。

您要么将模板更改为仅在执行ajax请求时返回表,要么在更新表之前更改javascript以从数据中提取表内容。

第一种方法可能更优雅。您可能会发现库django-pjax很有趣,它就是这样的。

但是,使用jQuery提取表格真的很简单。

var table_html = data.filter('#MyTable').html();
$('#MyTable').html(table_html);

答案 2 :(得分:1)

在views.py中,您可能应该返回这样的JSON数据,例如

import json
from django.http import HttpResponse
...
def my_ajax(request):
    data = {
        'key1': 'val1',
        'key2': 'val2',
    }
    return HttpResponse(json.dumps(data))