Reputation: 785
I passed a list data selectedOrder
from python to html as below.
return render_template(f"fillForm.html", items=selectedOrder)
I know there is a way to send a single data from html either by using input form or appending data to url as in /fillForm?sid=3&quantity=5
but I'm curious if I can send a list data from html back to python in such a manner as well. Obviously I can just store the data to some variable within python before passing it but given how my code is working, it would be better to directly get the data from html if possible. Not sure if this will matter, but I use flask and jinja2 template.
Upvotes: 1
Views: 2397
Reputation: 403
You could use an ajax request and send your list as a json. Flask provides the method request.get_json() to retrieve the json data received as a dict. Assuming you have jquery it would be like:
$.ajax({
url: "/your_route",
type: "POST",
contentType: "application/json;charset=UTF-8",
dataType: "json",
data: JSON.stringify({html_data: yourlist}),
success: function(response) {
console.log(response);
},
});
Then on flask side:
@app.route('/your_route')
def your_route():
data = request.get_json()
print(data['html_data']) # should print your list
# don't forget to return a success status
Upvotes: 2