问题描述
如何将JS对象转换为FormData
?
How can I can convert my JS Object to FormData
?
我要这样做的原因是,我有一个〜100表单字段值构造的对象.
The reason why I want to do this is, I have an object that I constructed out of the ~100 form field values.
var item = {
description: 'Some Item',
price : '0.00',
srate : '0.00',
color : 'red',
...
...
}
现在,我被要求将上载文件功能添加到我的表单中,这当然是无法通过JSON实现的,所以我打算迁移到FormData
.那有什么方法可以将我的JS对象转换为FormData
?
Now I am asked to add the upload file functionality to my form which, of-course is impossible via JSON and so I am planning on moving to FormData
. So is there any way that I can convert my JS object to FormData
?
推荐答案
如果有一个对象,则可以轻松地创建一个FormData对象,并将该对象的名称和值附加到formData.
If you have an object, you can easily create a FormData object and append the names and values from that object to formData.
您尚未发布任何代码,因此这是一个一般示例;
You haven't posted any code, so it's a general example;
var form_data = new FormData();
for ( var key in item ) {
form_data.append(key, item[key]);
}
$.ajax({
url : 'http://example.com/upload.php',
data : form_data,
processData : false,
contentType : false,
type: 'POST'
}).done(function(data){
// do stuff
});
> MDN 中的文档中还有更多示例>
There are more examples in the documentation on MDN
这篇关于将JS对象转换为表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!