Django结合JavaScript实现页面表格数据异步自动更新
解决Django表格异步自动更新问题
你的代码无效的核心原因是:Django模板标签({% for %})在页面首次渲染时就已经执行完毕,生成的JavaScript代码里是固定的旧数据,之后setInterval只是重复添加这些静态内容,并没有去后台请求最新数据。要实现异步更新,需要后端提供API接口返回最新数据,前端通过AJAX定时请求并动态渲染表格。
步骤1:后端新增API接口
在views.py中添加一个返回JSON数据的视图,用于提供最新的表格数据:
from django.http import JsonResponse from .models import New_tables def test(request): last_3 = New_tables.objects.filter(active=0).order_by('-id')[:3] last_new_table = reversed(last_3) return render(request, 'main/test.html', {"last_new_table":last_new_table}) # 新增API接口,返回最新数据的JSON def test_data_api(request): last_3 = New_tables.objects.filter(active=0).order_by('-id')[:3] last_new_table = reversed(last_3) # 将查询集转换为可序列化的字典列表 data_list = [] for item in last_new_table: data_list.append({ 'id': item.id, 'n': item.n, 'instrument': item.instrument }) return JsonResponse(data_list, safe=False)
在项目的urls.py中添加API路由:
from django.urls import path from . import views urlpatterns = [ path('test/', views.test, name='test'), path('test-data/', views.test_data_api, name='test-data-api'), # 新增API路由 ]
步骤2:修改前端JavaScript代码
将原来依赖模板标签的逻辑替换为AJAX请求,动态获取最新数据并渲染表格:
{% extends 'main/base.html' %} {%block content%} {% load static %} <script src="https://snipp.ru/cdn/jquery/2.1.1/jquery.min.js"></script> <table class="table table-hover table-dark"> <thead> <tr> <th class="text-white-50 bg-dark" style="font-size: 0.9em;" scope="col">Table</th> <th class="text-white-50 bg-dark text-center " style="font-size: 0.9em;" scope="col">N</th> <th class="text-white-50 bg-dark text-center " style="font-size: 0.9em;" scope="col">Type</th> <th class="text-white-50 bg-dark text-center " style="font-size: 0.9em;" scope="col">Quote</th> <th class="text-white-50 bg-dark text-center " style="font-size: 0.9em;" scope="col">Start</th> </tr> </thead> <tbody class="tbody"></tbody> </table> <script> function updateTable() { $('.tbody').empty(); // 发送AJAX请求获取最新数据 $.ajax({ url: '/test-data/', // 对应后端API路由 method: 'GET', dataType: 'json', success: function(data) { // 遍历数据生成表格行 data.forEach(item => { const row = ` <tr> <th class="text-white-50 bg-dark" scope="row">TBL000${item.id}</th> <td class="text-warning bg-dark">${item.n}</td> <td class="text-info bg-dark text-center">${item.instrument}</td> <td class="text-info bg-dark text-center"><img src='{% static "down.png" %}' width="20%" height="15%"></td> <td class="text-center" style="font-size: 0.9em;">....</td> </tr> `; $('.tbody').append(row); }); }, error: () => { $('.tbody').append('<tr><td colspan="5" class="text-center text-danger">加载数据失败</td></tr>'); } }); } // 页面加载时初始化表格 updateTable(); // 定时更新,建议设置为2-5秒(避免频繁请求增加服务器压力) setInterval(updateTable, 2000); </script> {%endblock content%}
关键说明
- 模板标签的执行时机:Django模板标签在服务器渲染页面时就已完成,无法在前端JavaScript中动态获取新数据,必须通过AJAX主动请求。
- 请求频率优化:将定时间隔从200毫秒调整为2000毫秒(2秒),过短的间隔会导致服务器负载过高,可根据实际需求调整。
- 扩展性:如果后续需要优化性能,可以考虑只返回新增/更新的数据(比如记录最后一次请求的最大ID,API只返回ID更大的数据),减少数据传输量。
内容的提问来源于stack exchange,提问作者Dixa Dex
相关产品推荐
相关产品推荐

