【问题标题】:Hide Bootstrap Modal after Python Flask template has renderedPython Flask 模板渲染后隐藏引导模式
【发布时间】:2016-12-07 12:37:03
【问题描述】:

我是 Python 和 Flask 的新手,所以我不确定我是否以正确的方式进行。 我有 2 个引导模式。一个显示一个通用的“加载时请稍候”微调器,当我的 python 从服务器获取 JSON 字符串,将字符串处理为 JSON 并将其存储时,应该显示该微调器。第二个模式仅在身份验证失败时显示。

目前,当我通过 localhost:5000/home 访问应用程序时,页面保持空白,而 python 从服务器获取数据并且仅在 GET 完成后呈现模板。因此,加载模式不会显示,因为页面仅在 GET 完成后呈现。

我需要渲染页面,显示加载模式,从服务器获取数据,然后在 GET 完成后隐藏加载模式,如果服务器在返回的 JSON 中返回身份验证失败标志,则显示身份验证失败模式.

这是我目前拥有的

index.html:

{% extends "base.html"%}
{%block content%}

    {% if not ready %}
        <script>
            $(document).ready(function(){       
                $("#pleaseWaitModal").modal("show");
            });
        </script>
    {% endif %}

    {% if not auth %}
        <script>
            $(document).ready(function(){       
                $("#failedValidationModal").modal();
            });
        </script>
    {% endif %}

    <div id="section">
        ...
    </div>
{%endblock%}

app.py:

def getJSON():
    auth=False

    infoCallURL = "https://myURL.com/?someParmas"
    r = requests.get(infoCallURL)
    obj = r.json()

    if obj['Application']['failure']:
        auth=False
    else:
        auth=True

    ready=True
    return ready,auth

@app.route('/',methods=['GET','POST'])
@app.route('/home',methods=['GET','POST'])
def home():
    ready = False
    auth = False
    ready,auth = getJSON()
    return render_template("index.html",ready=ready,auth=auth)

【问题讨论】:

  • 你是直接get请求还是ajax get请求?
  • 我正在使用 Python Requests 库:requests.get(infoCallURL)

标签: jquery python twitter-bootstrap flask


【解决方案1】:

对于加载模式,只需删除 {% if not ready %}{% endif %}。然后稍微修改代码以显示消息,直到站点加载:

$("#pleaseWaitModal").modal("show");
$(document).ready(function(){       
                $("#pleaseWaitModal").modal("hide");
});

Auth 部分更复杂。您正在同步调用 getJSON(),这意味着 render_template 始终具有此函数的结果。 如果您希望它异步加载,您必须使用 Ajax 或任何类似的东西在浏览器中加载数据。 http://api.jquery.com/jquery.getjson/ 解释如何加载 JSON:

$.getJSON( "https://myURL.com/?someParmas", function( data ) {
var json = JSON.parse(data);
if (json.Application.failure):
    $("#failedValidationModal").modal("show");
else:
    $("#failedValidationModal").modal("hide");
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 2015-11-24
    • 2018-09-28
    • 2021-04-21
    相关资源
    最近更新 更多