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!