繁体   English   中英

如何将数组数据从java脚本发送到flask

[英]how to send array data from java script to flask

如何将数组从 javascript 发送到 python 烧瓶。 ajax 没有将数组(值)返回到烧瓶路线。任何人都可以帮助解决这些错误

#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){}
  });




}

假设您的 html 代码是这样的:

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

这是您的 javascript 代码:

    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);
        })
    }

和你的烧瓶路线:

@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"

我使用了蓝图,所以不要对 @bp 或 site_bp.formit 感到困惑

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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