导入Formdata
时间: 2024-10-25 12:07:47 浏览: 43
在前端开发中,`FormData` 是一种内置对象,主要用于组织键值对数据,特别适合于发送异步请求,比如通过 `XMLHttpRequest` 或 Fetch API 向服务器提交表单数据。它是浏览器原生支持的,不需要额外的库。
在 JavaScript 中,你可以像下面这样创建并使用 `FormData`:
```javascript
// 创建一个新的 FormData 对象
let formData = new FormData();
// 添加键值对
formData.append('key1', 'value1');
formData.append('file', fileInput.files[0]); // 用于上传文件
// 发送异步请求
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/upload', true);
xhr.onload = function() {
if (xhr.status === 200) {
console.log('上传成功');
}
};
xhr.send(formData);
// 使用 Promise 和 Fetch API 的例子
fetch('/api/upload', {
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(data => console.log('响应:', data))
.catch(error => console.error('错误:', error));
```
阅读全文
相关推荐


















