When submitting a form, you may encounter the question of how to send the data using the Fetch API. By default, using FormData to send the body results in data being sent as multipart/form-data. However, if you're looking to send data as application/x-www-form-urlencoded, there are a few options available.
Using FormData automatically locks you into sending data in multipart/form-data format. To avoid this, you can manually create a URL-encoded string or a URLSearchParams object, rather than using FormData. Below is a code snippet that iterates through form elements and builds a URLSearchParams object:
const data = new URLSearchParams(); for (const pair of new FormData(formElement)) { data.append(pair[0], pair[1]); } fetch(url, { method: 'post', body: data, }) .then(…);
Note: You don't need to specify a Content-Type header explicitly.
Another experimental option is to create a URLSearchParams object and pass the FormData object directly, rather than looping through values:
const data = new URLSearchParams(new FormData(formElement));
While this method has some experimental support in browsers, it's recommended to test thoroughly before using it.
The above is the detailed content of How to Send Form Data as `application/x-www-form-urlencoded` with the Fetch API?. For more information, please follow other related articles on the PHP Chinese website!