简体   繁体   中英

How to pass javascript array of dictionary to flask

I have an array of dictionaries in javascript that I want to send as payload to a POST request to flask.

However, the array always gets sent empty.

Javascript:

{% for department in departments %}
        var department_id = "{{ department.id }}"
        var cardgroup = $("#cardgroups_{{ department.id }}").val();
        var doorgroup = $("#doorgroups_{{ department.id }}").val();

        data.push({
            department_id: department_id,
            cardgroup_id: cardgroup,
            doorgroup_id: doorgroup
        });
{% endfor %}

$.post("data/save-office/"+office, data={data: data}, function (data) {
        if (data['error']) {
            alert(data['error']);
        }
        else
            if (data['success']) {
                load_table();
            }
        });

python:

@app.post('/data/save-office/<office>')
def save_office(office):
    departments = request.args.getlist('data[]').  # departments = []

I tried to change departments to request.args.getlist('data') but it returned the same thing.

I also tried to use AJAX instead but it was basically the same thing.

Based on only provide an answer to your original question, you can pass an array to flask as the body of a POST request, Flask automatically handles JSON to dict conversion as-is. Consider this code block as an example of how to send that data:

 var my_json_array = [{ "key": "val" }, { "key": "val" }] async function postData(url = '', data = {}) { const response = await fetch(url, { method: 'POST', . headers: { 'Content-Type': 'application/json' }, body: data }); return response.json(); } postData('http://localhost:5000/test', my_json_array).then(data => { console.log(data); });

Note: I want to give credit to MDN for the fetch API sample I used on this post, visit https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch to know more about this new JavaScript API feature

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM