You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Django与Ajax实现表格数据的动态更新

实现无刷新更新表格的完整步骤

1. 改造后端views.py逻辑

首先调整视图函数,支持接收前端传递的过滤选项,区分普通请求和Ajax请求,Ajax请求返回渲染好的表格片段:

from django.http import JsonResponse
from django.template.loader import render_to_string

def display(request):
    temp_df_path = './temp_match.csv'
    # 选项映射,对应前端单选按钮的value
    option_map = {
        'option1': 'carnivores',
        'option2': 'herbivores',
        'option3': 'all'
    }
    # 优先取POST参数里的选项,默认显示全部
    selected_option = request.POST.get('inlineRadioOptions', 'option3')
    option = option_map[selected_option]
    animals_data = helper(temp_df_path, options=option)
    json_records = animals_data.reset_index().to_json(orient='records') 
    data = json.loads(json_records)
    context = {'d': data, 'data_columns': animals_data.columns}

    if request.method == 'POST' and request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest':
        # Ajax请求直接返回渲染好的表格行片段
        table_rows = render_to_string('_animal_table_rows.html', context=context)
        return JsonResponse({'table_rows': table_rows})
    
    # 普通请求返回完整页面
    return render(request, 'results.html', context=context)

2. 拆分模板公共片段

把原有表格里的动态行部分抽成单独的子模板_animal_table_rows.html,内容和你原有表格行渲染逻辑完全一致:

{% if d %}
{% for i in d %}
<tr>
    <th scope="row">
        {{forloop.counter}}
    </th>
    <!-- 保留你原有的列渲染逻辑即可 -->
    ...
</tr>
{% endfor %}
{% endif %}

然后修改原results.html里的表格部分,引入子模板,给tbody添加id方便后续替换:

<table class="table table-hover" id='results_table'>
    <thead>
        <tr>
            <th class="index_th">#</th>
            {% for col in data_columns %}
            <th>{{col}}</th>
            {% endfor %}
            <th class='action_cell'>Actions</th>
        </tr>
    </thead>
    <tbody id="table_body">
        {% include '_animal_table_rows.html' %}
    </tbody>
</table>

3. 修正前端Ajax代码

补充Django POST请求必需的CSRF令牌,传递选中的单选选项,回调中替换表格内容:

// 获取CSRF令牌的通用方法
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
const csrftoken = getCookie('csrftoken');

function change_content(event) {
    // 获取当前选中的单选按钮值
    const selectedOption = $('input[name="inlineRadioOptions"]:checked').val();
    $.post(
        "{% url 'display' %}",
        {
            'inlineRadioOptions': selectedOption,
            'csrfmiddlewaretoken': csrftoken
        },
        function(data, status, xhr){
            // 直接替换表格动态部分
            $('#table_body').html(data.table_rows);
        }
    );
    return false;
}

$(function () {
    $('.form-check-input').click(change_content);
});

内容的提问来源于stack exchange,提问作者Sashaank

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 11:15:05