JS FormData
时间: 2023-11-09 16:00:33 浏览: 43
FormData is a built-in JavaScript object that provides a way to easily construct a set of key/value pairs representing form fields and their values. It can be used to send form data to a server via AJAX requests, or to create and submit forms programmatically.
To create a new FormData object, use the following syntax:
```javascript
const formData = new FormData();
```
You can add fields to the FormData object using the `append()` method:
```javascript
formData.append('username', 'john');
formData.append('email', 'john@example.com');
```
You can also add files to the FormData object by passing a File object or a Blob object:
```javascript
const fileInput = document.querySelector('input[type="file"]');
formData.append('avatar', fileInput.files[0]);
```
To send the FormData object to a server using an AJAX request, use the `fetch()` function:
```javascript
fetch('/submit', {
method: 'POST',
body: formData
})
.then(response => {
// handle the response
})
.catch(error => {
// handle the error
});
```
The server can access the form data using the standard HTTP request body parsing mechanisms for the specific server-side framework or language being used.