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



如何从javascript发送数组到python flask。ajax没有返回数组(值)到flask路由。谁能帮助解决这些错误

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

和你的flask路由:

@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

最新更新