如何组合两个 javascript FormData 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22409667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to combine two javascript FormData objects
提问by u54r
I need to combine two FormData objects and post them using XMLHttpRequest. One of the forms contains file input.
我需要组合两个 FormData 对象并使用 XMLHttpRequest 发布它们。其中一种形式包含文件输入。
var formData = new FormData(document.forms.namedItem('form-ship'));
var poData = new FormData(document.forms.namedItem('po-form'));
// Combine them
var fData = $.extend(true, formData, poData);
It doesn't work when I use $.extend
or if I use serialize()
to combine the form that doesn't have file input. Any idea how to do this?
当我使用$.extend
或serialize()
用于组合没有文件输入的表单时,它不起作用。知道如何做到这一点吗?
采纳答案by Bergi
You cannot. FormData
is unfortunately not enumerable.
你不能。FormData
不幸的是不可枚举。
However, as you say only one of your forms does contain a file input. Then it should be possible to use serializeArray
on the other and append
to the data manually:
但是,正如您所说,只有一个表单确实包含文件输入。然后应该可以serializeArray
在另一个上使用并append
手动使用数据:
var formData = new FormData(document.forms['form-ship']); // with the file input
var poData = jQuery(document.forms['po-form']).serializeArray();
for (var i=0; i<poData.length; i++)
formData.append(poData[i].name, poData[i].value);
回答by andreshg112
I did it this way:
我是这样做的:
let formData = new FormData($("#f_articulos")[0]);
let formDataPrecios = new FormData($("#f_listado_precios")[0]);
for (var pair of formDataPrecios.entries()) {
formData.append(pair[0], pair[1]);
}