Home > Web Front-end > JS Tutorial > body text

How to Convert HTML5 FormData to JSON Without jQuery or Serialization?

DDD
Release: 2024-10-30 00:50:29
Original
663 people have browsed it

How to Convert HTML5 FormData to JSON Without jQuery or Serialization?

Converting HTML5 FormData to JSON: A Step-by-Step Guide

Problem: Converting the entries of a FormData object to JSON without jQuery or serializing the entire object.

Answer:

To convert the entries of a FormData object to JSON, follow these steps:

  1. Create an empty object to store the key/value pairs.
  2. Iterate over the FormData object using a loop or method like forEach.
  3. For each entry, set the key in the empty object to the entry's name and the value to its value.
  4. Convert the object to JSON using the JSON.stringify() method.

Example Using forEach:

<code class="js">var object = {};
formData.forEach(function(value, key){
    object[key] = value;
});
var json = JSON.stringify(object);</code>
Copy after login

Example Using ES6 Arrow Functions:

<code class="js">var object = {};
formData.forEach((value, key) => object[key] = value);
var json = JSON.stringify(object);</code>
Copy after login

Support for Multi Select Lists:

If your form contains multi select lists or other elements with multiple values, you can use the following approach:

<code class="js">var object = {};
formData.forEach((value, key) => {
    if(!Reflect.has(object, key)){
        object[key] = value;
        return;
    }
    if(!Array.isArray(object[key])){
        object[key] = [object[key]];    
    }
    object[key].push(value);
});</code>
Copy after login

Sending FormData to a Server:

If you intend to submit the form data to a server, you can skip the conversion to JSON and directly send the FormData object using an XMLHttpRequest or Fetch API request.

Caution:

The JSON.stringify() method may not support all types of objects. If your object contains unsupported types, you may need to implement a custom toJSON() method to specify the serialization logic.

The above is the detailed content of How to Convert HTML5 FormData to JSON Without jQuery or Serialization?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!