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:
Example Using forEach:
<code class="js">var object = {}; formData.forEach(function(value, key){ object[key] = value; }); var json = JSON.stringify(object);</code>
Example Using ES6 Arrow Functions:
<code class="js">var object = {}; formData.forEach((value, key) => object[key] = value); var json = JSON.stringify(object);</code>
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>
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!