When sending POST data containing values that are arrays or objects, jQuery follows a PHP convention of adding brackets to the field names. It's not a web standard, but because PHP supports it out of the box it is popular.
As a result, the correct way of handling POST data with lists on the Flask side is indeed to append square brackets to the field names, as you discovered. You can retrieve all values of the list using MultiDict.getlist()
:
request.form.getlist("x[]")
(request.form
is a MultiDict
object). This returns strings, not numbers. If you know the values to be numbers, you can tell the getlist()
method to convert them for you:
request.form.getlist("x[]", type=float)
If you don't want the additional brackets to be applied, don't use arrays as values, or encode your data to JSON instead. You'll have to use jQuery.ajax()
instead though:
$.ajax({
url: "/test",
type: "POST",
data: JSON.stringify({x: [1.0,2.0,3.0], y: [2.0, 3.0, 1.0]}),
contentType: "application/json; charset=utf-8",
success: function(dat) { console.log(dat); }
});
and on the server side, use request.get_json()
to parse the posted data:
data = request.get_json()
x = data['x']
This also takes care of handling the datatype conversions; you posted floating point numbers as JSON, and Flask will decode those back to float values again on the Python side.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…