Home  >  Article  >  Web Front-end  >  How to Convert HTML5 FormData to JSON for Client-Server Communication?

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

Linda Hamilton
Linda HamiltonOriginal
2024-10-26 18:33:30579browse

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>

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>

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>

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>

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>

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!

Statement:
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