【问题标题】:Flask app, button refreshes the browser. How to prevent it? [duplicate]Flask 应用程序,按钮刷新浏览器。如何预防? [复制]
【发布时间】:2018-08-25 03:58:51
【问题描述】:

我正在使用 Python Flask 构建一个简单的应用程序。我在使用此表单内的按钮时遇到问题。用户可以发表评论,然后按下按钮发表评论。

单击此按钮时,会触发表单操作(python 中的此操作,重定向到当前页面。)。现在,当单击按钮时,评论会发布在浏览器上,但浏览器会刷新。我不希望每次用户发表评论时都刷新浏览器。我应该如何让这个按钮不刷新页面并且仍然发布评论并在页面上显示评论而不刷新页面?

<form method="POST" action="{{ url_for('feed_app.message', message_id=fm.message.id) }}" role="form" enctype="multipart/form-data">
  {{ form.hidden_tag() }}
  <div class="form-group">
    {{ form.post(class='form-control', rows=1, style="background-color:#ffffff;width:200px;display:inline-block;") }}
    <input type="hidden" name="to_user" value="{{ user.username }}" />
    <button style="border-radius:5px;" type="submit" class="btn btn-success">Comment</button>
  </div>
</form>

这是python代码。

@feed_app.route('/message/<message_id>', methods=('GET', 'POST'))
def message(message_id):
    form = FeedPostForm()
    message = None

    user = User.objects.get(username=session.get('username'))
    message = Message.objects.filter(id=message_id).first()
    if not message:
        abort(404)

    if message and message.parent:
        abort(404)

    if form.validate_on_submit() and session.get('username'):
        # process post
        from_user = User.objects.get(username=session.get('username'))
        post = form.post.data

        # write the message
        comment = Message(
            from_user=from_user,
            text=post,
            message_type=COMMENT,
            parent=message_id
            ).save()

        return redirect(url_for('home_app.home', message_id=message.id))

    return render_template('feed/message.html',
        message=message,
        form=form
    )

是因为我将消息设置为重定向到当前页面吗?我不确定这是 HTML 问题还是 Flask 问题。

【问题讨论】:

  • 你需要使用ajax

标签: python html flask


【解决方案1】:

现在,当单击按钮时,评论会发布到浏览器上 但浏览器正在刷新

这就是同步请求的实际工作方式。

要实现您的目标,您需要使用异步请求 (AJAX) 或 websocket。如果您是 Web 开发新手 - 建议从使用 jQuery 的 AJAX 开始,一旦学习了这项技术 - 开始使用 websockets 将很容易。

AJAX 请求是常规的 HTTP 请求(GET、POST 等),但它们是 asynchronous,这意味着 1) 不需要刷新浏览器页面 2) 不需要等待服务器响应,因此前端脚本可以做另一个工作而不是等待响应。

Here 你可以找到更多关于使用 jQuery 发送 AjAX 请求的信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-26
    • 2019-11-20
    • 1970-01-01
    • 2019-03-04
    • 2018-01-09
    • 2017-07-13
    • 2013-03-19
    • 2012-11-03
    相关资源
    最近更新 更多