【发布时间】: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