题意:如何将 FormData
(HTML5 对象)转换为 JSON
问题背景:
How do I convert the entries from a HTML5 FormData
object to JSON?
如何将 HTML5 FormData
对象中的条目转换为 JSON?
The solution should not use jQuery. Also, it should not simply serialize the entire FormData
object, but only its key/value entries.
解决方案不应使用 jQuery。此外,解决方案不应仅仅序列化整个 FormData
对象,而应仅序列化其键/值条目。
问题解决:
You could also use forEach
on the FormData
object directly:
你也可以直接在 FormData
对象上使用 forEach
:
var object = {};
formData.forEach(function(value, key){
object[key] = value;
});
var json = JSON.stringify(object);
UPDATE:
And for those who prefer the same solution with 对于那些更喜欢使用相同解决方案的人, ES6 arrow functions:
var object = {};
formData.forEach((value, key) => object[key] = value);
var json = JSON.stringify(object);
UPDATE 2:
And for those who want support for multi select lists or other form elements with multiple values (since there are so many comments below the answer regarding this issue I will add a possible solution):
对于那些需要支持多选列表或其他具有多个值的表单元素的人(由于下面有很多关于这个问题的评论,我将提供一个可能的解决方案):
var object = {};
formData.forEach((value, key) => {
// Reflect.has in favor of: object.hasOwnProperty(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);
Here a Fiddle demonstrating the use of this method with a simple multi select list.
演示使用此方法的一个简单的多选列表。
UPDATE 3:
As a side note for those ending up here; in case the purpose of converting the form data to json is to send it through an XMLHttpRequest to a server you can send the FormData
object directly without converting it. As simple as this:
作为一个附带说明,给那些最终来到这里的人;如果将表单数据转换为 JSON 的目的是通过 XMLHttpRequest
发送到服务器,你可以直接发送 FormData
对象,而无需转换。只需要这样简单:
var request = new XMLHttpRequest();
request.open('POST', 'http://example.com/submitform.php');
request.send(formData);
See 参数 also Using FormData Objects on MDN for reference.
Or alternatively you can do the same with the modern day 或者,您也可以使用现代的 Fetch API:
fetch('http://example.com/submitform.php', {
method: 'POST',
body: formData
}).then((response) => {
// do something with response here...
});
See 参照 also Using The Fetch API on MDN for reference.
UPDATE 4:
As mentioned in one of the comments below my answer the JSON stringify
method won't work out of the box for all types of objects. For more information on what types are supported I would like to refer to 正如我答案下方的评论中提到的,JSON.stringify
方法并不适用于所有类型的对象。有关支持的类型的更多信息,我建议参考 the Description section in the MDN documentation of JSON.stringify.
In the description is also mentioned that:
在描述中还提到:
If the value has a toJSON() method, it's responsible to define what data will be serialized.
This means that you can supply your own toJSON
serialization method with logic for serializing your custom objects. Like that you can quickly and easily build serialization support for more complex object trees.
如何将 FormData
(HTML5 对象)转换为 JSON