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

How do I Convert HTML5 FormData to JSON?

DDD
Release: 2024-10-26 11:07:30
Original
1007 people have browsed it

How do I Convert HTML5 FormData to JSON?

Converting HTML5 FormData to JSON

Converting the entries of a HTML5 FormData object to JSON is a common task in web development. While there are various approaches to achieve this, the most straightforward and efficient method is to use the forEach() function directly on the FormData object.

var object = {};
formData.forEach(function(value, key){
    object[key] = value;
});
var json = JSON.stringify(object);
Copy after login

This approach iterates through each key-value pair in the FormData object and adds them to a new JavaScript object. The JSON.stringify() method is then used to convert the object to a JSON string.

Update: ES6 Arrow Functions

For those who prefer ES6 syntax, the same solution can be written using arrow functions:

var object = {};
formData.forEach((value, key) => object[key] = value);
var json = JSON.stringify(object);
Copy after login

Update 2: Support for Multi Value Form Elements

To support form elements with multiple values, such as multi-select lists, the following code can be used:

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);
});
var json = JSON.stringify(object);
Copy after login

Update 3: Direct Submission via XMLHttpRequest and Fetch API

Sending FormData directly to a server without conversion is possible using the XMLHttpRequest object or Fetch API:

<code class="javascript">var request = new XMLHttpRequest();
request.open('POST', 'http://example.com/submitform.php');
request.send(formData);</code>
Copy after login
<code class="javascript">fetch('http://example.com/submitform.php', {
  method: 'POST',
  body: formData
}).then((response) => { 
  // do something with response here... 
});</code>
Copy after login

Update 4: JSON Serialization of Complex Objects

Custom serialization logic can be defined for complex objects through the toJSON() method.

The above is the detailed content of How do I Convert HTML5 FormData to JSON?. 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!