Passing Javascript Array To Flask
Solution 1:
Flask has a built in object called request. In request there is a multidict called args.
You can use request.args.get('key')
to retrieve the value of a query string.
from flask import request
@app.route('/example')defexample():
# here we want to get the value of the key (i.e. ?key=value)
value = request.args.get('key')
Of course this requires a get request (if you use a post then use request.form
). On the javascript side you can make a get request using pure javascript or jquery.
I'm going to use jquery in my example.
$.get(
url="example",
data={key:value},
success=function(data) {
alert('page content: ' + data);
}
);
This is how you pass data from the client into flask. The function portion of the jquery code is how you pass data from flask to jquery. Let's say for example you have a view called /example and from the jquery side you pass in a key value pair of "list_name":"example_name"
from flask import jsonify
defarray(list):
string = ""for x inlist:
string+= x
return string
@app.route("/example")defexample():
list_name = request.args.get("list_name")
list = get_list(list_name) #I don't know where you're getting your data from, humor me.
array(list)
return jsonify("list"=list)
and in the success function in jquery you'd say
success=function(data) {
parsed_data = JSON.parse(data)
alert('page content: ' + parsed_data);
}
Note that flask does not allow for top level lists in json response for security reasons.
Post a Comment for "Passing Javascript Array To Flask"