【问题标题】:Flask flash message no longer works when using ajax使用 ajax 时,Flask flash 消息不再起作用
【发布时间】:2015-02-15 13:14:25
【问题描述】:

当我使用表单操作提交表单数据时,我能够闪回消息。

查看表单:

@app.route('/register')
def register():
    return render_template('register.html')

注册.HTML

<form action="{{ url_for('processRegister') }}" method=post>
        <dl>
          <dt>email:
          <dd><input type="text" name="email" id="email">
          <div id="emailBlank" class="error"><font color="red">email cannot be blank</font></div>
          <div id="emailFormat" class="error"><font color="red">invalid email format</font></div>
          <dt>Password:
          <dd><input type="password" name="password" id="password">
          <div id="pwBlank" class="error"><font color="red">password cannot be blank</font></div>
          <dt>Enter password again:
          <dd><input type="password" name="password2" id="password2">
          <div id="pw2Blank" class="error"><font color="red">verify password field cannot be blank</font></div>
          <dd><input type="submit" value="submit" id="submit"><br><br>
        </dl>
        </form>
      <a href="{{ url_for('verifyEmailForm') }}">send another verification email</a>
    {% endblock %}

现在我正在使用 ajax,我的 flash 消息不再出现。

$(document).ready(function(){
   (code removed for clarity)

            if (error == false) {
                $.ajax({
                  type: "POST",
                  url: "/processRegister",
                  data: { varEmail: email, varPassword: pw}
                });//ajax call
            }//end if
        });//submit
    });//load validate.js
});//doc rdy

我对处理表单数据的看法:

@app.route('/processRegister', methods=['POST'])
    def processRegister():
        if request.method == 'POST':
            email = request.form['varEmail']
            flash("message -----> " + email)
        return render_template('register.html')

我的布局页面使用下面的sn-p进行闪烁:

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

【问题讨论】:

  • 您的“布局页面”有 Flash 渲染代码,但它是否包含在您的 register.html 模板中?

标签: jquery python ajax flask


【解决方案1】:

闪现的消息是stored as part of the session,在服务器端渲染模板时检索。客户端 JavaScript 无法访问会话 cookie。即使是这样,它也不容易在 JavaScript 中解码。即使您可以对其进行解码,也假定会话是一个 cookie,而不是存储在服务器或其他东西上。

如果您想呈现一些消息以响应 AJAX 请求,您应该在响应中发送这些消息并在您用 JavaScript 编写的处理程序中呈现它们。使用重定向时提供闪烁消息是为了方便,但由于您使用的是 AJAX,因此您可以跳过此中间步骤,直接返回消息。

【讨论】:

    【解决方案2】:

    问题在于 AJAX 调用不会重新渲染 DOM。

    Javascript 将收到作为调用结果的渲染模板。

    我想在返回的对 jQuery 的响应中,flash 消息就在其中。

    浏览器不会将返回的值视为要呈现的内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-11
      • 2017-03-28
      • 2018-05-26
      • 1970-01-01
      • 2017-05-14
      • 2014-04-18
      相关资源
      最近更新 更多