javascript - 如何使用 ajax 提交带有文件上传的表单
问题描述
我有一个很长的多步表格。其中有文本输入和上传文件选项。我正在尝试使用 Ajax 将其提交给 PHP。我已经尝试过FormData
,但我不确定如何发送其他选择和文本输入字段。
https://developer.mozilla.org/en-US/docs/Web/API/FormData
我怎样才能做到这一点?
const addListingForm = $('#add-listing-form');
addListingForm.on('submit', function (e) {
console.log('Submitted');
const formData = new FormData(document.getElementById('add-listing-form'));
$.ajax({
url: `${SITE_URL}/private/shared/process`,
type: 'post',
data: formData,
processData: false,
contentType: false,
success: function (resp) {
console.log(resp);
},
error: function (err) {
console.log(err);
},
});
e.preventDefault();
});
<form action="" method="post" enctype="multipart/form-data" id="add-listing-form">
<input type="text" name="title" id="title" class="custom-input" />
<input type="text" name="tagline" id="tagline" class="custom-input" />
<input type="file" name="halal-certificate" class="custom-file-input" id="halal-certificate">
<input type="file" name="list-photos[]" multiple class="custom-file-input" id="list-photos">
<button type="submit">
Submit
</button>
</form>
解决方案
尝试这个
let title = document.getElementById("title").value;
let firstFile= document.getElementById("list-photos[]").files[0];
let formData = new FormData();
formData.append("file1", firstFile);
formData.append("title", title );
//and add more
或者
let title = document.getElementById("title").value;
let firstFile= document.getElementById("list-photos[]").files[0]; // file from input
let req = new XMLHttpRequest();
let formData = new FormData();
formData.append("file1", firstFile);
formData.append("title", title );
req.open("POST", '/upload/image');
req.send(formData);
推荐阅读
- delphi - Delphi - 在运行时复制控件和所有属性
- html - 具有较短文本量的引导不规则间距
- c# - 在同步方法中运行没有 Wait() 的 Task.Run() 有什么影响?
- mysql - 尝试使用 mySQL 设置 keycloak 但由于时区问题而失败
- r - 在 R 中生成实验设计数据
- javascript - 将一个反应组件放在(z 轴)另一个上
- javascript - 如何检查函数是否已完全执行并将完成标志存储在 JavaScript 的全局变量中
- javascript - HTML 和 JS:如何在 div 中使用 textContent 在单击按钮后显示文本而不让文本快速消失?
- html - 移动设备上出现白圈问题
- python - python 正则表达式如何捕获所有可能是可选的组?