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

How to Convert HTML5 FormData to JSON for Client-Server Communication?

Linda Hamilton
Release: 2024-10-26 18:33:30
Original
640 people have browsed it

How to Convert HTML5 FormData to JSON for Client-Server Communication?

Converting HTML5 FormData to JSON

Converting HTML5 FormData objects to JSON allows for the serialization of form data into a machine-readable format. This is useful for transmitting data between the client and server.

Method Using a Custom Object and JSON.stringify

To convert FormData entries to JSON without jQuery or serializing the entire object:

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

Update 1: ES6 Arrow Functions

Using ES6 arrow functions:

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

Update 2: Support for Multi-Value Elements

For multi-select lists or other form elements with multiple values:

<code class="javascript">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);</code>
Copy after login

Update 3: Direct Transmission of FormData

For sending FormData to a server via XMLHttpRequest:

<code class="javascript">var request = new XMLHttpRequest();
request.open('POST', 'http://example.com/submitform.php');
request.send(formData);</code>
Copy after login

Or using the Fetch API:

<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: Custom toJSON Method for Complex Objects

For custom objects, define a toJSON method to serialize their content. Refer to the MDN documentation for more information on JSON.stringify limitations.

The above is the detailed content of How to Convert HTML5 FormData to JSON for Client-Server Communication?. 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