admin管理员组

文章数量:1279055

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

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=".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>

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

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./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>
Share Improve this question asked Dec 28, 2017 at 22:17 user2242044user2242044 9,25329 gold badges104 silver badges172 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

I've looked for the answer to this question on many pages and none of them worked until I found the one that releases the AJAX call so that the rerender is allowed to take place:

$('form').on('submit', function(event) {
   $.ajax({
      type: 'POST',
      url:  "{{ url_for( 'myServerFunction' ) }}",
      data: JSON.stringify({'myId':bunchOfIds}),
      contentType: "application/json",
      success:function(response){ document.write(response); }       
   })

The most important line is the success line that releases the document so that it can be rerendered.

When you send POST request through AJAX, the request es 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.

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.

Ok, why don't you just send a 'yes or no' flag from your flask app. Since you want to show the success or failure message without page refresh, getting jquery to update the DOM when your flask app returns a result. Something like return message in your flask app might do the trick acpained by success: function(e)({ $('body').append(e);});. Can't produce more code due to word length restriction on my phone, but tweaking your code along mine gets the job done. Cheers!

本文标签: javascriptflask rendertemplate doesn39t work on AJAX postStack Overflow