Javascript formData 到数组

Javascript formData to array

如何 "convert" 将 formData 转换为数组?

这对我来说效果很好,但似乎并不适用于所有浏览器: https://developer.mozilla.org/en-US/docs/Web/API/FormData/entries

有没有办法在支持旧版浏览器的情况下做同样的事情?

var form_data = new FormData(this);
var form_array = [];

for(var pair of formData.entries()) {
   form_array[pair[0]] = pair[1];
}

更新

我尝试了这个但没有成功:

var entries = form_data.entries();

for (var i = 0; i < entries.length; i++) {
    console.log(entries[i]);
}
console.log(entries);

给了

Iterator {}

你可能想参加 look at this w3shcools example

var x = document.getElementById("frm1");
var text = "";
var i;
for (i = 0; i < x.length ;i++) {
    text += x.elements[i].value + "<br>";
}

可能是

var form_data = new FormData(this);
var array_data = [...form_data]; // ya this works

现代浏览器上你可以使用Array.from:

const form_array = Array.from(form_data);

来自 MDN:

The Array.from() method creates a new, shallow-copied Array instance from an array-like or iterable object.

然而,对于 旧版浏览器(没有 polyfill),您必须手动解压迭代器:

var formData = new FormData(document.forms[0])
var formArray = [];

formData.forEach(function(value) {
  formArray.push(value);
});

console.log(formArray);
<form>
  <input name="foo" value="5">
  <input name="bar" value="42">
</form>

如果您想保存名称-值对,您应该遍历表单:

var form = document.forms[0];
var formArray = [];

for (var i = 0; i < form.length; i += 1) {
  formArray.push({ name: form[i].name, value: form[i].value });
}

console.log(formArray);
<form>
  <input name="foo" value="5">
  <input name="bar" value="42">
</form>