首页 > 解决方案 > 如何在 ajax 中呈现作为 Flask 应用程序响应发送的模板?

问题描述

我正在使用 Python Flask 应用程序,该应用程序将基本的 html 和 javascript 用于 Web 部件。

我正在使用 ajax 发布请求将数据从 UI 发送到后端。处理完数据后,我从 Python 烧瓶应用程序返回带有 render_template 的响应。但我无法理解如何在网络浏览器上使用 ajax 来呈现它。

python烧瓶API返回这个:

    @app.route("/execution_pipeline", methods=['POST', 'GET'])
def execution_pipeline():
    try:
        if request.method == 'POST':
            inputMap = request.get_json()
            print(inputMap)
            ###I have my code here###                                                               
            return render_template('demo.html', location=minio_results_file_location)
           

    except ReferenceError as e:
        return "It is a {} Provide proper referaece of file path"

“demo.html”是代码目录中的一个模板,我想在成功执行时加载它

而ajax函数如下:

$.ajax({
            type: "POST",
            url: "execution_pipeline",
            data: JSON.stringify(data),
            contentType : "application/json",
            success: function(response) {
                 window.location.href = response.redirect;
            }
        });

但是在我们尝试加载此 Ajax 响应的网页上,我得到的 URL 未找到。

有什么解决办法吗?还是我做错了什么?

标签: javascriptjqueryajaxflaskredirect

解决方案


从烧瓶中导入 jsonify 和 url_for:

from flask import jsonify, url_for

并尝试像这样返回到 ajax 调用:

@app.route("/execution_pipeline", methods=['POST', 'GET'])
def execution_pipeline():
    try:
        if request.method == 'POST':
            inputMap = request.get_json()
            print(inputMap)
            ###I have my code here###                                                               
            return jsonify({'redirect': url_for('demo.html', location=minio_results_file_location)})
           

    except ReferenceError as e:
        return "It is a {} Provide proper referaece of file path"

推荐阅读