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

Update Django Template every 5 seconds Fail

我正在构建 Django 项目并尝试使用 AJAX。我需要使用每 5 秒从 Raspberri Pi 传来的新数据来刷新我的模板。数据存储在 SQLite 数据库中。

我是 Django 的新手,也是 Ajax.I 的新手,尝试从一些基础的东西开始,这是我的代码:

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>

在运行时我的网页崩溃并分析服务器日志,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

如有任何建议,我们将不胜感激。 提前致谢。

您只想更新 table,但是 ajax 请求 data return 将包含整个 html,包括脚本.

您要么在执行 ajax 请求时将模板更改为仅 return table,要么更改 javascript 以提取 table 更新 table.

之前数据中的内容

第一种方法可能更优雅。您可能会发现库 django-pjax 很有趣,它会做类似这样的事情。

但是,使用 jQuery 提取 table 确实 容易。

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

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

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

这对我有用:

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>

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

  • Creating a JSON response using Django and Python
  • Parsing JSON objects for HTML table
  • How to serialize to JSON a list of model objects in django/python