【发布时间】:2020-05-15 19:16:05
【问题描述】:
我希望发生这种情况:用户从表单下拉列表中进行选择,表单将变量传递给 Flask 服务器 app_route 函数,该函数调用由输入的参数动态过滤的 sql,并将数据表返回给浏览器。
在 Flask 中,我设置了一个 app_route,它提供 url_for 一个 json 文件。返回的对象是一个 json dict,它是由用户提交的表单中的参数过滤的 sql 查询的结果。表单的action函数发布到这个函数,并返回json dict url。
Datatable 需要数据的 url。它似乎不允许我使用 jinja 模板变量。我的冲突是我需要重定向/呈现具有数据表的 html 页面的模板并返回包含子字典的 url。
我要渲染模板('the_page_with_datatable.html', my_local_json_dict_variable)。
我可以从表单提交调用的 app_route 下调用的函数中 render_template('the_page_with_datatable.html') 或 return(my_local_json_dict_variable) 并分配给 url_for 位置,但不能同时使用两者。
这是怎么做到的?
所以我已经可以使用普通的 jinja 变量返回一个数据 frame_to_html,但我特别想要数据表功能。我不想渲染任何其他类型的表格。我还可以使用静态 sql 渲染数据表,其中我使用了对 api 的 sql 响应。问题是提交表单操作返回一个 url,而我需要两个 - json url 和 render_template url。
HTML/JS
<form class="form-inline" id="my_form" action="get_data" method="POST">
<div class="form-group">
<select name="year" class="selectpicker form-control">
{% for yr in years %}
<option value="{{ yr }}">{{ yr }}</option>
{% endfor %}
</select>
<select name="month" class="selectpicker form-control">
{% for month in months %}
<option value="{{ month }}">{{ month }}</option>
{% endfor %}
</select>
</div>
<button type="submit" class="btn btn-default">Go</button>
</form>
<table id="values_table" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Number</th>
<th>Date</th>
<th>values_€</th>
</tr>
</thead>
</table>
<script>
function setupData() {
$(document).ready(function () {
$('#values_table').DataTable( {
dom: 'Bfrtip',
"ajax": {
"url": "/get_data",
"dataType": "json",
"dataSrc": "data",
"contentType":"application/json"
},
"columns": [
{"data": "PersonName"},
{"data": "PersonNumber"},
{"data": "Date"},
{"data": "values_€"},
]
});
});
});
}
$( window ).on( "load", setupData );
</script>
Flask routes
#renders page with select form and datatable
@app.route("/values_select" , methods=['GET','POST'])
def values_select():
years, months = api().values_select()
return render_template('values_select.html', years=years, months=months)
#get json data for datatable to parse from url
@app.route("/get_data" , methods=['GET','POST'])
def get_data():
year = request.form.get('year')
month = request.form.get('month')
data = assets_api().values(month, year)
return jsonify(data=data)
【问题讨论】:
标签: json ajax forms flask datatables