繁体   English   中英

重定向后如何显示警报指示器?

[英]How to display an alert Indicator after being redirected?

我有一个页面在成功单击提交按钮后将用户重定向到主页。

我想显示这样的指标:

在此处输入图像描述

从提交按钮重定向回主页后,位于主页导航栏下方。

我怎样才能做到这一点? 对不起,我是 web 开发的新手。

我相信您可以在 flask 中创建一个响应,该响应重定向并设置一个 cookie。 就像是

from flask import make_response

response = make_response(redirect('/homepage'))
response.set_cookie('show_success_flash', 'true')

return response

然后,在您的 JS 端,您可以读取 cookie,如果它是真的,则显示消息。 然后,您可以在关闭 flash 消息时删除 cookie,也可以在 setTimeout 后将其删除。 就像是:

// homepage.js


const cookie = import 'js-cookie'

if (cookie.get('show_success_flash') {
  const successFlash = document.getElementById('success_flash_message')

  if (successFlash.style.display === 'none') {
    successFlash.style.display = 'block'
  }
}

Flask 支持闪现消息。 https://flask.palletsprojects.com/en/1.1.x/patterns/flashing/

在我看来,这比使用 cookie 显示临时弹出窗口要好。

因此,要设置闪烁的消息,请执行以下操作:

@app.route('/sample')
def sample():
    if successCheck()
        flash('You were successfully logged in')
    return redirect("/index")

在模板中,要检索闪烁的消息,请执行以下操作:

{% with messages = get_flashed_messages() %}
  {% if messages %}
    <ul class=flashes>
    {% for message in messages %}
      <li>{{ message }}</li>
    {% endfor %}
    </ul>
  {% endif %}
{% endwith %}

您还可以使用类别:

# Route
flash(u'Invalid password provided', 'error')
# Template
{% with messages = get_flashed_messages(with_categories=true) %}
  {% if messages %}
    <ul class=flashes>
    {% for category, message in messages %}
      <li class="{{ category }}">{{ message }}</li>
    {% endfor %}
    </ul>
  {% endif %}
{% endwith %}

或者这个模板选项:

# Template
{% with errors = get_flashed_messages(category_filter=["error"]) %}
{% if errors %}
<div class="alert-message block-message error">
  <a class="close" href="#">×</a>
  <ul>
    {%- for msg in errors %}
    <li>{{ msg }}</li>
    {% endfor -%}
  </ul>
</div>
{% endif %}
{% endwith %}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM