简体   繁体   中英

how to send array data from java script to flask

how to send array from javascript to python flask. the ajax is not returning the array (values)to flask route .Can anyone please help with these error

#flask route
@app.route('/admin',methods = ['POST','GET'])
def admin():
    if request.method == "POST":
        a=request.form.getlist("contacts[]")
        return str(a)
#js code
window.onload = function(){}
var btn = document.querySelector("#btn");
btn.onclick = function(){
    var div= document.createElement("div");
    div.innerHTML = generateit();
    document.getElementById("box").appendChild(div);
}

function generateit()
{
 return "<input type='text' class='txt' placeholder='Enter party name' required>&nbsp<input type='text' class ='txt1' placeholder = 'Enter region' required>&nbsp<input type='text' class='txt2' placeholder='Enter name' required>&nbsp<button id ='btn' onclick='removeit(this);'>Remove</button>";
}

function removeit(btn)
{
    document.getElementById("box").removeChild(btn.parentNode);
}

values =[]
$.ajax({
    url:'{{url_for("admin")}}',
    type:'POST',
    data:{contacts:values},
    success:function(res){}
  });




}

let assume that your html code is like this:

<butoon id="generate_row">generate row</butoon>
<div id="box">
    <button onclick="send()">send</button>
</div>

here is your javascript code:

    window.onload = function () {
        var btn = document.querySelector("#generate_row");
        var box = document.getElementById("box");

        btn.onclick = function () {
            var div = document.createElement("div");
            var row_num = box.querySelectorAll("#box > div").length + 1;  // add 1 to start from 1
            div.innerHTML = generateit(row_num);
            box.appendChild(div);
        }
    }

    function generateit(row_num) {
        return `<input type='text' placeholder='Enter party name' required>
                <input type='text' placeholder = 'Enter region' required>
                <input type='text' placeholder='Enter name' required>
                <button id ='btn_remove${row_num}' onclick='removeit(this);'>Remove</button>`;
    }

    function removeit(btn) {
        document.getElementById("box").removeChild(btn.parentNode);
    }

    function send() {
        values = [];
        let divs = document.querySelectorAll("#box > div");

        divs.forEach(innerDiv => {
            let innerDivValues = [];
            let textInputs = innerDiv.querySelectorAll("input[type='text']");
            textInputs.forEach(inputElement => innerDivValues.push(inputElement.value))
            values.push(innerDivValues);
        });
       
        
        fetch('{{url_for("site_bp.formit")}}', {
            method: "POST",
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({contacts: values})
        }).then(async response => await response.json())
        .then(data => {
            console.log(data);
        })
    }

and your flask route:

@bp.route('/formit',methods = ['POST','GET'])
def formit():
    if request.method == "POST":
        contacts=request.json.get("contacts", None)
        for contact in contacts:
            print (contact)
        return {"contacts": contacts}
    return "not post request"

i used blueprints so don't be confused about that @bp or site_bp.formit

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