简体   繁体   中英

How to bind AJAX data to a Flask Python App?

I am doing some groundwork on building my first python flask web application. I have sorted out most of the details I need on the server side, but I have few questions on how to implement things on client side.

My Application is going to be a single page application with data populated dynamically depending on user action.

Say, I have a template called index.html which has a menu selection on left hand side and a table structure on the right hand side of the template. When an user selects an option from menu, I will post an AJAX request from the client to server and the flask app routes returns a JSON response.

This is where my issue is. I know how to fill in a table data when rendering a page.I can use

render_template('index.html',tabledata = tabledata )

in my server side to send table data and use

{% for data in tabledata %}
<tr> data </tr>
{% endfor %}

in my client side, I can use a code as above.

But since I am planning to use AJAX requests, I am not sure how to populate the table data returned from AJAX request in already rendered flask template.

I searched for answer and I have found out that I have to build the table dynamically using Javascript. But I want to know is there any better way to fill in the template? I am trying to avoid building html table using javascript.

Thanks

If you want to populate a table using data using AJAX, it's generally recommended to use JSON for API endpoints (adding an XSS to your site by inserting HTML into the DOM is a bad idea). You can do this by simply returning a dictionary ( you shouldn't ever return JSON lists from an endpoint ), like so:

@app.route("/some/url")
def route():
    return flask.jsonify(**{"a": "dict", "returned": "becomes", "a": "JSON object"})

You can then use AJAX to get the object and populate your table using JavaScript. You should note that Flask has nothing to do with client-side code (apart from serving it to the client).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM