Flask使用ajax时,闪现消息不再起作用

4
当我使用表单操作提交表单数据时,我能够返回提示信息。
表单视图:
@app.route('/register')
def register():
    return render_template('register.html')

Register.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时,我的提示信息不再出现了。
$(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')

我的布局页面使用以下代码段进行闪烁:

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

您的“布局页面”具有 Flash 渲染代码,但是否已在您的 register.html 模板中包含? - Celeo
2个回答

12

Flashed messages(闪现消息)是作为会话的一部分存储的,并在服务器端呈现模板时检索。 会话cookie对客户端JavaScript不可访问。即使可以,它在JavaScript中也不容易解码。 即使您可以解码它,这也假定会话是一个Cookie而不是存储在服务器或其他地方的东西。

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


1
问题在于AJAX调用不会重新渲染DOM。
Javascript将会接收到渲染后的模板作为调用结果。
我想在返回给jQuery的响应中,闪存消息就在其中。
浏览器不会将返回值视为需要渲染的内容。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接