Sending array data with jquery and flask

前端 未结 2 1288
夕颜
夕颜 2020-12-03 13:10

I need to send data from a html page back into my Python application:

$.post(\"/test\", {x: [1.0,2.0,3.0], y: [2.0, 3.0, 1.0]}, function(dat) {console.log(da         


        
相关标签:
2条回答
  • 2020-12-03 13:24

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

    var filter={}
     filter.startDate=$('#quant1').val(); 
     filter.endDate=$('#quant2').val(); 
     var checkedItems = [], counter = 0;
        $("#appNamesSelector div.active").each(function(idx, li) {
            checkedItems[counter] = $(li).text();
            counter++;
        });
    filter.apps=checkedItems;
    console.log($.param(filter));
        $.ajax({ type: "GET",   
     url: "/drilldown",
     data : filter  
    });
    

    Image shows how the array is passed into the server.

    0 讨论(0)
  • 2020-12-03 13:37

    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.

    0 讨论(0)
提交回复
热议问题