Home > Web Front-end > JS Tutorial > How to Send Form Data as `application/x-www-form-urlencoded` with the Fetch API?

How to Send Form Data as `application/x-www-form-urlencoded` with the Fetch API?

Mary-Kate Olsen
Release: 2024-11-04 15:34:02
Original
657 people have browsed it

How to Send Form Data as `application/x-www-form-urlencoded` with the Fetch API?

Posting Form Data with the Fetch API Using Application/x-www-form-urlencoded

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.

FormData with Multipart/Form-Data Format

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(…);
Copy after login

Note: You don't need to specify a Content-Type header explicitly.

URLSearchParams with FormData

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));
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template