[英]Django render list of json data via ajax
我想向前端呈現一個數據框,以便我可以在我的 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 的“成功:”部分做一些事情,但它要么顯示“對象”,要么只顯示文本。
我應該如何在“成功:”部分進行編碼以獲取整個 {{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')
謝謝
您可以使用.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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.