【问题标题】:Django render list of json data via ajaxDjango通过ajax渲染json数据列表
【发布时间】:2021-03-04 20:32:47
【问题描述】:

我想在前端渲染一个数据框,以便在我的 html 页面上创建一个表格。

通常,如果我使用简单渲染(不涉及 ajax),我会将其传输到 json 数据列表,然后将其渲染到 html 页面:

my_function.py:
def df_to_json(df):
    json_records = df.reset_index().to_json(orient ='records') 
    data = [] 
    data = json.loads(json_records)
    return data 

json 数据如下所示:

[{"category":0, "sales":135, "cost": 197, "em_id":12},
{"category":0, "sales":443, "cost": 556, "em_id":12},
{"category":2, "sales":1025, "cost": 774, "em_id":15},...]

然后在我的views.py和based.html页面中:

views.py:
def home(request):
    dict_search = request.GET.get('inputtxt_from_html')
    df = my_function.myfunction1(dict_search)
    df_json = my_function.df_to_json(df)
    return render(request, 'base.html', {'df_json': df_json})

based.html:
<div class="container">
    <table class="table table-dark table-striped" id='table1'>
        <tbody>
        {% if df_json%}
        {% for i in df_json%}
            <tr>
                <td>{{i.sales}}</td>
                <td>{{i.cost}}</td>
                <td>{{i.em_id}}</td>
            </tr>
        {% endfor %}
        {% endif %}
        </tbody>
    </table>
</div>

现在的问题是我想做类似上面的事情,但这次输入来自 ajax。

似乎我无法直接获取我的 html 页面的渲染结果 {{df_json}}。我试图在我的 ajax 的“成功:”部分做一些事情,但它要么显示“对象”,要么只显示文本。

我应该如何在“success:”部分编码以获得整个 {{df_json}},这样我就不必更改我的 based.html 页面?或者实际上我必须在所有基于视图的 ajax 页面中做一些不同的事情?

my_ajax.js:
$(document).ready(function(){
    $("#button1").click(function() {
        $.ajax({
            url: '',
            type: 'GET',
            data: {
                inputtxt_from_html: $("#input_field").val()
            },
            success: function(response){
                -- I don't know how to write. belowing is just example
                $("#table1").append('<li>' + response.json_dict + '</li>')
            }
        });
    });
});

新视图.py:

def home(request):
    dict_search = request.GET.get('inputtxt_from_html')
    if request.is_ajax():
        df = my_function.myfunction1(dict_search)
        df_json = my_function.df_to_json(df)
        return JsonResponse({'df_json': df_json}, status=200)
    return render(request, 'base.html')

谢谢

【问题讨论】:

    标签: javascript python jquery django ajax


    【解决方案1】:

    您可以使用 .each 循环遍历 JSON 数组 的值,并使用 value.keyname 使用 JSON 数组 中的值生成您的 trs td,然后追加这会生成 html 到您的 table

    演示代码

    //suppose this your json response
    var response = [{
        "category": 0,
        "sales": 135,
        "cost": 197,
        "em_id": 12
      },
      {
        "category": 0,
        "sales": 443,
        "cost": 556,
        "em_id": 12
      },
      {
        "category": 2,
        "sales": 1025,
        "cost": 774,
        "em_id": 15
      }
    ]
    $(document).ready(function() {
     /*$("#button1").click(function() {
          $.ajax({
           url: '',
           type: 'GET',
           data: {
             inputtxt_from_html: $("#input_field").val()
           },
           success: function(response) {*/
      var html = '';
      //loop through json array
      $(response).each(function(index, value) {
        html += "<tr><td>" + value.sales + "</td><td>" + value.cost + "</td><td>" + value.em_id + "</td></tr>" //append datas in tr
      })
      $("#table1 tbody").append(html) //add generated html in table1
      /* }
        });
      });*/
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="container">
      <table class="table table-dark table-striped" id='table1'>
        <tbody>
    
          <tr>
            <td>{{i.sales}}</td>
            <td>{{i.cost}}</td>
            <td>{{i.em_id}}</td>
          </tr>
    
        </tbody>
      </table>
    </div>

    【讨论】:

    • 这正是我所需要的。感谢您的解决方案。
    猜你喜欢
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 2012-06-11
    • 1970-01-01
    • 2016-12-19
    • 2014-04-15
    相关资源
    最近更新 更多