大家好,
我有一个表单,里面有多个字段。此外,表单正在使用 ajax 通过表单数据方法提交到 php 文件。
以下是提交表单数据的javascript代码。
$(".update").click(function(){
$.ajax({
url: 'post_reply.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
data.append('image',$('#picture').get(0).files[0]);
data.append('body' , $('#body').val());
data.append('uid', $('#uid').val());
return data;
}(),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
$('#picture').val('');
$('#body').val('');
});
下面是实际的形式:
<textarea name=body id=body class=texarea placeholder='type your message here'></textarea>
<input type=file name=image id=picture >
<input name=update value=Send type=submit class=update id=update />
此表单和 javascript 可以正常工作。但是,我试图使用这个单一的 type=file 字段属性将多个文件上传到 php 文件。就像现在一样,它一次只能处理一个文件。如何调整表单和 javascript 代码以处理多个文件上传?
如有任何帮助,我们将不胜感激。
谢谢!
最佳答案
这是您可以访问的全局 ajax、html 和 php。让我知道它是否适合您。
// Updated part
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
// Full Ajax request
$(".update").click(function(e) {
// Stops the form from reloading
e.preventDefault();
$.ajax({
url: 'post_reply.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
data.append('body' , $('#body').val());
data.append('uid', $('#uid').val());
return data;
}(),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
$('#picture').val('');
$('#body').val('');
});
更新的 HTML:
<form enctype="multipart/form-data" method="post">
<input id="file" name="file[]" type="file" multiple/>
<input class="update" type="submit" />
</form>
现在,在 PHP 中,您应该能够访问您的文件:
// i.e.
$_FILES['file-0']
关于javascript - 表单数据通过ajax连同文本字段上传多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43239665/