Вопрос:
Я создаю проект 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
Любое предложение будет оценено по достоинству. Заранее спасибо.
Лучший ответ:
Это сработало для меня:
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>
Эти ответы помогли мне найти решение:
- Создание ответа JSON с использованием Django и Python
- Разбор объектов JSON для таблицы HTML
- Как сериализовать в JSON список объектов модели в django/python
Ответ №1
Вы только хотите обновить таблицу, но data возвращаемые запросом ajax, будут содержать весь html, включая скрипты.
Вы либо хотите изменить шаблон, чтобы возвращать таблицу только при выполнении запроса ajax, либо изменить javascript для извлечения содержимого таблицы из данных перед обновлением таблицы.
Первый подход, вероятно, более изящный. Вы можете найти библиотеку django-pjax интересной, она делает что-то вроде этого.
Однако извлечение таблицы с помощью jQuery очень просто.
var table_html = data.filter(‘#MyTable’).html(); $(‘#MyTable’).html(table_html); Ответ №2
В views.py вы, вероятно, должны возвращать данные JSON, подобные этому, например
import json from django.http import HttpResponse … def my_ajax(request): data = { ‘key1’: ‘val1’, ‘key2’: ‘val2’, } return HttpResponse(json.dumps(data))