我有带有附件输入的表单:
<form enctype="multipart/form-data" action="" method="post" id="sendInvoiceForm">
.....
<div class="templateDiv">
<span class="invoice_email_label">Email attachments:</span>
<input name="email_attachment[]" type="file" multiple="">
</div>
<div class="templateDiv">
<button id="send_invoice_btn" class="bigButton redButton">Send</button>
</div>
</form>
和js:
data = new FormData($("#sendInvoiceForm")[0]);
data.append('flagSend', 1);
data.append('send_invoice_subject', sendInvoiceSubject);
....
$.ajax({
type: 'POST',
data: data,
processData: false,
contentType: false,
url: sJSUrlSavePdfInvoiceToServer,
dataType: 'json',
success: function (data) {
if (data.msg === 'Error. This invoice number exists.') {
alert(data.msg);
} else {
...
}
},
error: function () {
alert('error');
}
});
我测试了一下,似乎没有用。所有数据都能顺利通过,但文件无法通过。 当我print_r $ _FILES时,它是空的。我怎么了谢谢。
答案 0 :(得分:0)
这对我有用-
var form_data = new FormData($('#submitForm')[0]);
$.ajax({
url: "<?php echo base_url() . 'backends/update_documents' ?>",
type: "POST",
dataType: 'json', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function (res) {
// console.log(res);
},
error: function (xhr, ajaxOptions, thrownError) {
//console.log(xhr);
}
});
您可以尝试使用缓存:false 并提及按钮,输入=“ button”
答案 1 :(得分:0)
这就是我的工作方式 附加表单数据,
var formData = new FormData(your_form);
// for multiple files , because i need to check
new_files是类,我使用是因为我正在动态创建表单
$.each($(".new_files"), function (i, obj) {
// console.log(obj.files);
$.each(obj.files, function (j, file) {
var max_size = 5120000;
var file_type= file.type;
var match = ["image/jpeg", "image/png", "image/jpg", "application/pdf"];
// after validation etc
// append formdata
formData.append('file[' + j + ']', file);
});
});
// if you want something else,
formData.append("id", $('#kreditornr').val());
// ajax
$.ajax({
type: "POST",
url: "url",
data: formData,
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function (data) {
// success
}
});
答案 2 :(得分:-2)
首先删除dataType: 'json'
然后如果仍然显示错误,请替换
data = new FormData($("#sendInvoiceForm")[0]);
使用
data = new FormData($("#sendInvoiceForm").prop('files')[0]);
答案 3 :(得分:-2)
尝试通过:
发送数据 data: $('#sendInvoiceForm').serialize();