使用 Flask 在单页应用程序中提交表单而无需重新加载

eri*_*ric 7 html javascript python flask

我正在用 python 开发一个单页 Flask 应用程序。要更改页面的内容,我只需调用一个 javascript 函数来隐藏一个 div 并显示另一个。

其中一个 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>
Run Code Online (Sandbox Code Playgroud)

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;
    }
Run Code Online (Sandbox Code Playgroud)

和烧瓶应用程序(我实际上没有让它返回???):

@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 ???
Run Code Online (Sandbox Code Playgroud)

我很感激任何建议!谢谢!

eri*_*ric 0

我最终使用的解决方案有点旧,但效果很好。我通过向表单添加按钮将表单重定向到不可见的 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>
Run Code Online (Sandbox Code Playgroud)

和 JavaScript 函数:

function redirect(elemid, tgt, sh1, sh2){
        document.getElementById(elemid).target = tgt;
        document.getElementById(elemid).submit();

        var callFunction;
        callFunction = show_and_hide(sh1, sh2);
    }
Run Code Online (Sandbox Code Playgroud)

show_and_hide 函数是我用来淡出一个 div 并淡入另一个 div 的函数。