[ACCEPTED]-Sending array data with jquery and flask-flask

Accepted answer
Score: 23

When sending POST data containing values 20 that are arrays or objects, jQuery follows 19 a PHP convention of adding brackets to the field names. It's not a web standard, but because 18 PHP supports it out of the box it is popular.

As 17 a result, the correct way of handling POST 16 data with lists on the Flask side is indeed 15 to append square brackets to the field names, as 14 you discovered. You can retrieve all values 13 of the list using MultiDict.getlist():


(request.form is a MultiDict object). This 12 returns strings, not numbers. If you know the values 11 to be numbers, you can tell the getlist() method 10 to convert them for you:

request.form.getlist("x[]", type=float)

If you don't want 9 the additional brackets to be applied, don't 8 use arrays as values, or encode your data 7 to JSON instead. You'll have to use jQuery.ajax() instead 6 though:

    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 5 the posted data:

data = request.get_json()
x = data['x']

This also takes care of 4 handling the datatype conversions; you posted 3 floating point numbers as JSON, and Flask 2 will decode those back to float values again 1 on the Python side.

Score: 1

You can use the flask function request.args.getlist('apps[]') to get 2 the list from the js object you are passing 1 to the server

var filter={}
 var checkedItems = [], counter = 0;
    $("#appNamesSelector div.active").each(function(idx, li) {
        checkedItems[counter] = $(li).text();
    $.ajax({ type: "GET",   
 url: "/drilldown",
 data : filter  

Image shows how the array is passed into the server.

More Related questions