Home > Web Front-end > JS Tutorial > How to Post Form Data as \'application/x-www-form-urlencoded\' with Fetch API?

How to Post Form Data as \'application/x-www-form-urlencoded\' with Fetch API?

Barbara Streisand
Release: 2024-11-03 05:28:02
Original
913 people have browsed it

How to Post Form Data as

Posting Form Data with the Fetch API

When using the FormData interface in Fetch API to post form data, it is important to understand its default behavior. By default, it sends data using the "multipart/form-data" format, which is not compatible with the "application/x-www-form-urlencoded" format.

If you want to post form data as "application/x-www-form-urlencoded" using Fetch API, you can follow these steps:

  1. Convert FormData to URLSearchParams: Use a loop to iterate through the FormData object and append each key-value pair to a URLSearchParams object.

    <code class="javascript">const data = new URLSearchParams();
    for (const pair of new FormData(formElement)) {
        data.append(pair[0], pair[1]);
    }</code>
    Copy after login

    OR, use the experimental method:

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

    Note: Ensure your browser supports the latter method before using it.

  2. Send data using Fetch API: Make a POST request with the body set to the URLSearchParams object. Do not specify a Content-Type header, as the default will be "application/x-www-form-urlencoded".

    <code class="javascript">fetch(url, {
        method: 'post',
        body: data,
    })
    .then(…);</code>
    Copy after login

The above is the detailed content of How to Post Form Data as \'application/x-www-form-urlencoded\' with 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