【发布时间】:2015-09-07 09:56:54
【问题描述】:
真的只是在寻找一些建议。我正在构建的网站上有一个小表格:
- 姓名
- 电子邮件
- 号码
- 简历(附件)
我以前做过表格,但是添加了附件后我不知道该怎么做。
我习惯使用 jQuery 的序列化功能。有没有类似的东西可以用来在我的 Ajax 调用中发布?我似乎无法在网上找到很多信息..
【问题讨论】:
标签: php jquery ajax forms email-attachments
真的只是在寻找一些建议。我正在构建的网站上有一个小表格:
我以前做过表格,但是添加了附件后我不知道该怎么做。
我习惯使用 jQuery 的序列化功能。有没有类似的东西可以用来在我的 Ajax 调用中发布?我似乎无法在网上找到很多信息..
【问题讨论】:
标签: php jquery ajax forms email-attachments
对于 AJAX 请求,您不能真正使用 .serialize() 函数。您需要使用FormData()。你也可以放一个进度条。我们需要先检查支持:
function supportAjaxUploadWithProgress() {
return supportFileAPI() && supportAjaxUploadProgressEvents() && supportFormData();
function supportFileAPI() {
var fi = document.createElement('INPUT');
fi.type = 'file';
return 'files' in fi;
};
function supportAjaxUploadProgressEvents() {
var xhr = new XMLHttpRequest();
return !! (xhr && ('upload' in xhr) && ('onprogress' in xhr.upload));
};
function supportFormData() {
return !! window.FormData;
}
}
下一步是使用 AJAX 提交表单:
var form = document.getElementById('form-id');
var formData = new FormData(form);
你必须有这些 HTML:
var form = document.getElementById('the-form');
form.onsubmit = function() {
var formData = new FormData(form);
formData.append('file', file);
var xhr = new XMLHttpRequest();
// Add any event handlers here...
xhr.open('POST', form.getAttribute('action'), true);
xhr.send(formData);
return false; // To avoid actual submission of the form
}
<form id="the-form" action="/upload/path" enctype="multipart/form-data">
<input name="file" type="file">
<input type="submit" value="Upload" />
</form>
【讨论】: