Home >Web Front-end >JS Tutorial >How to Convert HTML5 FormData Entries into JSON without jQuery?

How to Convert HTML5 FormData Entries into JSON without jQuery?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-29 19:48:02209browse

How to Convert HTML5 FormData Entries into JSON without jQuery?

Transforming HTML5 FormData Entries into JSON

Converting HTML5 FormData entries to JSON is essential when working with form data and passing it to server endpoints or APIs. Here's a solution that does not rely on jQuery or serialization:

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

For enhanced readability and conciseness, you can use ES6 arrow functions:

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

Handling Multi-Value Form Elements:

If you need to support multi-select lists or other form elements with multiple values, you can expand the solution as follows:

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);

Direct Submission to Server without Conversion:

If your goal is to submit FormData to a server, you can bypass the JSON conversion step and directly send the FormData object itself via Ajax or Fetch API:

var request = new XMLHttpRequest();
request.open('POST', 'http://example.com/submitform.php');
request.send(formData);
fetch('http://example.com/submitform.php', {
  method: 'POST',
  body: formData
}).then((response) => { 
  // Handle server response here... 
});

Considerations for Non-Serializable Objects:

Remember that the JSON stringify method may not handle all types of objects without additional customization. If you encounter issues with object serialization, you can define your own toJSON() method on the object to specify the desired serialization behavior.

The above is the detailed content of How to Convert HTML5 FormData Entries into JSON without jQuery?. 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