Ajax Flask在服务器端检索多个表单的数据



我使用ajax将多个表单数据作为一个表单数据对象发送到python-flask。就像这里的例子一样。

在下面的代码中,我使用ajax将两个表单的数据发送到flask。我无法在服务器端检索到它,但我设法在python上使用request.files获取了文件。

但我无法检索或查看附加到ajax请求的id为"的表单数据对象;形式-2";。

我如何才能看到在后端的第二个表单上填写的输入值。

<html>

<body>
<form id="form1">
<input type="file" name="file[]" multiple id="file-input" />
<form>

<form id="form2">
<div class="preference">
<label for="cheese">Do you like cheese?</label>
<input type="checkbox" name="cheese" id="cheese">
</div>
<select name="course">
<option value="1">HTML</option>
<option value="2">CSS</option>
<option value="3">JAVA SCRIPT</option>
</select>

<form>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
<script>
$("input[type='file']").on("change", function(ev) {
ev.preventDefault(); // Prevent browser default submit.
var form_data = new FormData()
var all_files    = document.querySelector('input[type=file]').files
var totalfiles = all_files.length;


for (var i = 0; i < totalfiles; i++) {

console.log(all_files[i]);
form_data.append("files[]", all_files[i]);

console.log("Added " + (1 + i)+ " files in formdata");




}

console.log("added all files completely! ...appending advance options");

var formdata2 = new FormData(document.getElementById('form-2'));


form_data.append("advance_options", formdata2)


console.log("successfully appended..calling ajax func");

send_request_to_flask(form_data);

});

</script>

<script>
function send_request_to_flask(form_data_parameter){


$.ajax({
url: "http://127.0.0.1:5000",
type: "POST",
data: form_data,
contentType: false,
cache: false,
dataType: 'json',
processData:false,
withCredentials:true,
beforeSend: function(xhr) {

},
xhr: function() {  
var xhr = $.ajaxSettings.xhr();
if(xhr.upload){ 
xhr.upload.addEventListener('progress', function(event){
var percent = 0;
if (event.lengthComputable) {
percent = Math.ceil(event.loaded / event.total * 100);
}
console.log(percent)
}, false);
}
return xhr;
},
success: function (msg) {
console.log(msg)


},
error: function(data){


console.log(data);
}
});

}





</script>
</body>
</html>

不能将一个表单数据对象附加到另一个表单对象中,必须将第二个表单中的字段附加到第一个表单数据目标中。

最新更新