[英]Submit a Form in a Single Page Application using Flask Without Reloading
我正在使用python中的单页Flask应用程序。 要更改页面的内容,我只需调用一个隐藏一个div并显示另一个div的javascript函数。
其中一个div包含一个用户可以上传文件的表单,我通过python脚本运行该文件来解析文件中的数据。
问题是,在执行代码后,Flask似乎希望我重定向到新页面。 我宁愿返回一个触发器来简单地运行我的javascript函数。
HTML表单:
<form class='upload-form' id='upload-form' action="/upload" method='POST' enctype="multipart/form-data" onsubmit="return show_and_hide('load', 'upload')">
<input type="file" name='file' value="Browse...">
<input type="submit" value='Upload'>
</form>
Javascript函数:
var callFunction;
function show_and_hide(div_in, div_out){
var shower = document.getElementById(div_in);
var hider = document.getElementById(div_out);
var hider_items = hider.children;
var i;
for(i = 0; i < hider_items.length; i++){
hider_items[i].style.animation = "hide 1s";
}
callFunction = setTimeout(change_div, 1000, div_in, div_out);
var shower_items = shower.children;
var n;
for(n = 0; n < shower_items.length; n++){
shower_items[n].style.animation = "show 1s";
}
return true;
}
烧瓶应用(我实际上没有它返回???):
@app.route('/upload', methods=['POST', 'GET'])
def upload_file():
f = request.files['file']
new_file_name = str(uuid.uuid1()) + '.zip'
f.save(os.path.join('uploads/', new_file_name))
path = 'uploads/' + new_file_name
return ???
我很感激任何建议! 谢谢!
您需要使用JavaScript将文件发布到Flask,因为提交HTML表单将始终重定向您。 以下是使用AJAX的示例如何异步上传文件?
Flask需要所有视图函数(路由)来返回发送给客户端的响应。 您可以重新设置空字符串和200状态,以便让Flask知道您已成功处理了请求。
@app.route('/upload', methods=['POST', 'GET'])
def upload_file():
f = request.files['file']
new_file_name = str(uuid.uuid1()) + '.zip'
f.save(os.path.join('uploads/', new_file_name))
path = 'uploads/' + new_file_name
return '', 200
我最终使用的解决方案有点旧,但效果很好。 我通过向表单添加一个按钮将表单重定向到不可见的iframe:
<input type="button" id="double-analysis-button" value='Correlate' style='width:250px' onclick="redirect('double-analysis-form', 'double-analysis-iframe', 'graph-loading', 'graph-display')">
<iframe class="uploader" id="double-analysis-iframe" name="double-analysis-iframe" src="" frameborder="0"></iframe>
和javascript函数:
function redirect(elemid, tgt, sh1, sh2){
document.getElementById(elemid).target = tgt;
document.getElementById(elemid).submit();
var callFunction;
callFunction = show_and_hide(sh1, sh2);
}
show_and_hide函数是我用来淡化一个div和另一个div的函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.