Home > Web Front-end > JS Tutorial > How do you send form data with Fetch API in different formats?

How do you send form data with Fetch API in different formats?

Susan Sarandon
Release: 2024-11-03 03:43:31
Original
747 people have browsed it

How do you send form data with Fetch API in different formats?

Posting Form Data with Fetch API

When utilizing the Fetch API to submit form data, there are two main formats to consider:

Multipart/Form-Data

When using FormData to construct the request body, the data will automatically be sent in the multipart/form-data format. This is a default behavior of FormData and cannot be modified.

Application/x-www-form-urlencoded

To send the data in application/x-www-form-urlencoded format, you have a few options:

1. URL-Encoded String:

<code class="javascript">fetch("api/xxx", {
    body: "[email protected]&password=pw",
    headers: {
        "Content-Type": "application/x-www-form-urlencoded",
    },
    method: "post",
});</code>
Copy after login

2. URLSearchParams Object:

<code class="javascript">const data = new URLSearchParams();
data.append("email", "example@email.com");
data.append("password", "mypassword");

fetch("api/xxx", {
    body: data,
    method: "post",
});</code>
Copy after login

Note that specifying the Content-Type header is not necessary when using URLSearchParams, as it automatically sets the correct content type.

3. URLSearchParams from FormData:

<code class="javascript">const data = new URLSearchParams(new FormData(formElement));

fetch("api/xxx", {
    body: data,
    method: "post",
});</code>
Copy after login

This option allows you to pass the FormData object directly to create the URLSearchParams object. However, it may have limited browser support, so be sure to test it thoroughly before using it.

The above is the detailed content of How do you send form data with Fetch API in different formats?. 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