flask render_template doesn't work on AJAX pos

2020-07-22 18:27发布

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

3条回答
放我归山
2楼-- · 2020-07-22 19:07

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.

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.

查看更多
虎瘦雄心在
3楼-- · 2020-07-22 19:10

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 accompained 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!

查看更多
劫难
4楼-- · 2020-07-22 19:24

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.

查看更多
登录 后发表回答