【问题标题】:How to change table data with Django and Ajax如何使用 Django 和 Ajax 更改表数据
【发布时间】:2022-01-03 10:58:47
【问题描述】:

我有一个 pandas 数据框,我在 Django 模板中显示如下

views.py

def display(request):
    if request.method == 'POST':

        temp_df_path = './temp_match.csv'
        option = 'all'
        animals_data = helper(temp_df_path, options=option)
        
        json_records = animals_data.reset_index().to_json(orient='records') 

        data = []
        data = json.loads(json_records)
        
        context = {'d': data, 'data_columns': animals_data.columns}

        return render(request, 'results.html', context=context)

这里我展示了一个使用辅助函数过滤的 DataFrame。在模板中,我有一组单选按钮,我可以使用它们更改 option 变量。这是我的模板

<div class="container center">
    <div class="table_options action_panel_centered">
        <div class="form-check form-check-inline">
            <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio3" value="option3"
                checked>
            <label class="form-check-label" for="inlineRadio3">Show all animals</label>
        </div>
        <div class="form-check form-check-inline">
            <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio1" value="option1">
            <label class="form-check-label" for="inlineRadio1">Show only carnivores</label>
        </div>
        <div class="form-check form-check-inline">
            <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio2" value="option2">
            <label class="form-check-label" for="inlineRadio2">Show only herbivores</label>
        </div>
    </div>
</div>

<div class="container-fluid root center">
    <div class="table_container">
        <table class="table table-hover" id='results_table'>
            <tr>
                <th class="index_th">#</th>
                {% for col in data_columns %}
                <th>{{col}}</th>
                {% endfor %}
                <th class='action_cell'>Actions</th>
            </tr>
            {% if d %}
            {% for i in d %}
            <tr>
                <th scope="row">
                    {{forloop.counter}}
                </th>
                ...
        </table>
    </div>
</div>

我想使用 Ajax 更改内容。我怎么做?我有一个Ajax函数如下

function change_content(event) {
    $.post(
         url : {% url 'display' %},
         success: function(data, status, xhr){
            //do something with your data
        }
    );
    return false;
}

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

【问题讨论】:

    标签: python jquery django ajax


    【解决方案1】:
    1. 创建一个单独的 HTML 页面,其中仅包含 您希望在按钮更改时加载(通常)。
    2. 然后在后端写一个函数来渲染这个页面。通过必要 用于过滤查询并将数据传递到正在呈现的页面的函数的参数。
    3. 之后在 前端并使用必要的方法调用上述函数 参数,在成功响应中只需将表内容替换为 传入的数据。

    【讨论】:

      猜你喜欢
      • 2020-04-18
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 2019-12-11
      • 1970-01-01
      • 1970-01-01
      • 2015-10-10
      • 2017-08-17
      相关资源
      最近更新 更多