烧瓶render_template在AJAX帖子上不起作用 [英] flask render_template doesn't work on AJAX post

查看:305
本文介绍了烧瓶render_template在AJAX帖子上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网站向Flask路线发布AJAX.

I have a site that makes an AJAX post to a Flask route.

我知道有许多类似的问题(请不要将其标记为重复项)使用AJAX成功方法来处理响应.在我的简化示例中,这是可行的,但是实际代码中的路线是从数据库中提取一堆数据,这些数据被渲染到多个表中.我不希望不使用JavaScript重写所有表数据更新,因此我只需要重新呈现模板即可.

I know there are many similar questions (please don't mark as duplicate) that use the AJAX success method to handle the response. That would work in my simplified example, but the route in my actual code is pulling a bunch of data from a database that gets rendered to multiple tables. I'd prefer not to rewrite all the table data updates in JavaScript, so I really just need to re-render the template.

python:

from flask import Flask, render_template, request
app = Flask(__name__)


@app.route('/', methods=['GET', 'POST'])
def hello_world(message=None):
    return render_template('test.html', message=message)


app.run()

html

<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <script>
        $(document).ready(function () {
            $('#mybutton').click(function () {

                $.post(window.location.href, {'test': 'test'});

            });
        });

    </script>
</head>
<body>
{{ message }}
<button id="mybutton" name="mybutton" type="button">Click Me!</button>
</body>
</html>

推荐答案

当您通过AJAX发送POST请求时,该请求来自javascript,并且flask的响应数据将存储在Javascript对象中.浏览器本身不会直接发送或接收任何内容,因此不会重新呈现页面.

When you send POST request through AJAX, the request comes from javascript and response data from flask will be stored in a Javascript object. The browser itself doesn't directly send or receive anything, so it won't re-render the page.

您需要在Flask应用中定义另一个终结点,以为POST请求返回json数据,并使用AJAX使用返回的json数据来操作DOM.

You need to define another endpoint in your Flask app to return json data for your POST request, and use AJAX to manipulate the DOM using the returned json data.

这篇关于烧瓶render_template在AJAX帖子上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆