Ajax Flask 网络应用程序错误
Ajax error on Flask web app
我正在制作一个小型 Flask 应用程序。目前,我要实现的功能之一是:
- 上传 Excel 文件
- 使用
pandas
进行一些数据清理
- 在网页上使用 AJAX 和
bootstrap-table
显示结果 dataframe
我卡住了。这是我的代码:
views.py
@app.route('/extract', methods=['GET', 'POST'])
def extract_excel():
file = request.files['file']
# SKIP: data extract and transform process, I get a valid dataframe
df_json = df.to_json(orient="records", force_ascii=False)
df_json = str(df_json)
return df_json
index.html
<body>
<div>
<form action="/extract" method="post" enctype="multipart/form-data">
<input type="file" name="file"></input>
<input type="text" name="upload_date" placeholder="2018-01-01"></input>
<button type="submit" id="showtable">preview</button>
</form>
</div>
</body>
<body>
<table data-toggle="table" id="WorkTable">
<thead>
<tr>
<th>...</th>
<th>...</th>
<th>...</th>
<th>...</th>
</tr>
</thead>
</table>
</body>
<script>
$(document).ready(function() {
$('#showtable').bind("click", function(){
$.ajax({
type: "POST",
url: "/extract",
dataType: "json",
success: function (msg) {
$("#WorkTable").bootstrapTable('load', msg);
},
error: function () {
alert("wrong");
}
});
});
});
</script>
我猜问题出在 ajax 部分。因为我查看了Console,发现很快就出现了POST http://127.0.0.1:5000/extract 400 (BAD REQUEST)
。我想它应该在文件上传和 return 响应时执行?但是我不知道怎么解决。
正如 Daniel Roseman 的评论所述,您需要发送表单数据(通过 jQuery .ajax
调用中的 data
属性)。您可能想看看 FormData docs.
您可能还会发现,确保您是 运行 Flask in debug mode 很有用,这样您可以获得更详细的错误消息。
我正在制作一个小型 Flask 应用程序。目前,我要实现的功能之一是:
- 上传 Excel 文件
- 使用
pandas
进行一些数据清理 - 在网页上使用 AJAX 和
bootstrap-table
显示结果
dataframe
我卡住了。这是我的代码:
views.py
@app.route('/extract', methods=['GET', 'POST'])
def extract_excel():
file = request.files['file']
# SKIP: data extract and transform process, I get a valid dataframe
df_json = df.to_json(orient="records", force_ascii=False)
df_json = str(df_json)
return df_json
index.html
<body>
<div>
<form action="/extract" method="post" enctype="multipart/form-data">
<input type="file" name="file"></input>
<input type="text" name="upload_date" placeholder="2018-01-01"></input>
<button type="submit" id="showtable">preview</button>
</form>
</div>
</body>
<body>
<table data-toggle="table" id="WorkTable">
<thead>
<tr>
<th>...</th>
<th>...</th>
<th>...</th>
<th>...</th>
</tr>
</thead>
</table>
</body>
<script>
$(document).ready(function() {
$('#showtable').bind("click", function(){
$.ajax({
type: "POST",
url: "/extract",
dataType: "json",
success: function (msg) {
$("#WorkTable").bootstrapTable('load', msg);
},
error: function () {
alert("wrong");
}
});
});
});
</script>
我猜问题出在 ajax 部分。因为我查看了Console,发现很快就出现了POST http://127.0.0.1:5000/extract 400 (BAD REQUEST)
。我想它应该在文件上传和 return 响应时执行?但是我不知道怎么解决。
正如 Daniel Roseman 的评论所述,您需要发送表单数据(通过 jQuery .ajax
调用中的 data
属性)。您可能想看看 FormData docs.
您可能还会发现,确保您是 运行 Flask in debug mode 很有用,这样您可以获得更详细的错误消息。