Javascript 如何将数组值添加到新的 FormData?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11208488/
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 add an array value to new FormData?
提问by Dan
On form submission I'm using jQuery to gather data including files and creating a FormData Object of the form values using:
在提交表单时,我使用 jQuery 收集数据,包括文件并使用以下方法创建表单值的 FormData 对象:
var formData = new FormData($("form#formid")[0]);
but how can I add another value and it's key to this FormData Object?
但是我怎样才能添加另一个值,它是这个 FormData 对象的关键?
回答by Esailija
var formData = new FormData($("form#formid")[0]);
formData.append("key", "value")
See https://developer.mozilla.org/en/XMLHttpRequest/FormData
回答by Calvein
You can iterate over all the fields in the form and add them to the FormData
quite easily this way :
您可以遍历表单中的所有字段,并通过FormData
这种方式轻松地将它们添加到表单中:
var formData = new FormData();
$("form#edit-account").serializeArray().forEach(function(field) {
formData.append(field.name, field.value)
});?
回答by Tony
$( 'form' ).submit(function ( e ) {
var data;
data = new FormData();
data.append( 'file', $( '#file' )[0].files[0] );
$.ajax({
url: 'http://hacheck.tel.fer.hr/xml.pl',
data: data,
processData: false,
type: 'POST',
success: function ( data ) {
alert( data );
}
});
e.preventDefault();
});
});
回答by Alex
var data = new FormData(),
fields = $("#myForm").serializeArray();
$.each( fields, function( i, field ) {
data.append(field.name, field.value);
});
回答by Lucky
You can also use FormData.set().
您还可以使用FormData.set()。
The difference between FormData.set and append() is that if the specified key already exists, FormData.set will overwrite all existing values with the new one, whereas append() will append the new value onto the end of the existing set of values.
FormData.set 和 append() 之间的区别在于,如果指定的键已经存在,FormData.set 将用新值覆盖所有现有值,而 append() 会将新值附加到现有值集的末尾.
Syntax:
语法:
formData.set(name, value);