Sending array data using jquery and bulb

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

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

on server:

 @app.route('/test', methods=['POST']) def test(): print request.form.keys() print dir(request.form) print request.form["x[]"] return jsonify({"Mean": 10.0}) 

To the great surprise, the keys

 ['y[]', 'x[]'] 

and

 print request.form["x[]"] 

leads to 1.

What is the right way to do this?

+2
source share
2 answers

When sending POST data containing values ​​that are arrays or objects, jQuery follows the PHP convention of adding parentheses to field names . This is not a web standard, but because PHP supports it out of the box, it is popular.

As a result, the correct way to process POST data with lists on the Flask side is really to add square brackets to the field names, as you discovered. You can get all list values ​​using MultiDict.getlist() :

 request.form.getlist("x[]") 

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

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

If you do not want to use extra brackets, do not use arrays as values ​​or encode your data in JSON instead. You will have to use jQuery.ajax() , 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 analyze the published data:

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

It also allows you to handle data type conversions; you sent the floating point numbers as JSON, and Flask decrypts them again again for the float values ​​on the Python side.

+13
source

You can use the request.args.getlist('apps[]') bulb function to get a list from the js object that you pass 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 }); 

The image shows how the array is transferred to the server.

+1
source

Source: https://habr.com/ru/post/970069/


All Articles