简体   繁体   English

Django通过ajax呈现json数据列表

[英]Django render list of json data via ajax

I want to render a data frame to the front-end so that I can create a table on my html page.我想向前端呈现一个数据框,以便我可以在我的 html 页面上创建一个表格。

Usually, if I use simple render (without ajax involves), I transfer it to a list of json data and then render it to html page:通常,如果我使用简单渲染(不涉及 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 

The json data look like this: 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},...]

Then in my views.py and based.html page:然后在我的 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>

The problem now is that I want to do something like above but this time the input is from ajax.现在的问题是我想做类似上面的事情,但这次输入来自ajax。

And it seems like I cannot directly get the render results {{df_json}} for my html page.似乎我无法直接获得我的 html 页面的渲染结果 {{df_json}}。 I tried to do something in the "success:" part of my ajax, but it either show "Object" or just text.我试图在我的 ajax 的“成功:”部分做一些事情,但它要么显示“对象”,要么只显示文本。

How shouldI code in "success:" part to get the entire {{df_json}}, so that I don't have to change my based.html page?我应该如何在“成功:”部分进行编码以获取整个 {{df_json}},以便我不必更改我的 based.html 页面? Or acturally I have to do something different in all view, based, ajax pages?或者实际上我必须在所有视图,基于,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>')
            }
        });
    });
});

New view.py:新视图.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')

Thank you谢谢

You can use .each loop to iterate through values of JSON Array and generate your trs td with the value from JSON Array using value.keyname and then append this generated html to your table .您可以使用.each循环遍历JSON 数组的值并使用value.keyname使用来自JSON 数组的值生成您的trs td ,然后将此生成的 html 附加到您的table

Demo Code :演示代码

 //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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM