无法填充 FormData 对象

Can't populate FormData object

正在尝试找出 FormData,但无法填充它。其他类似的问题是因为 form 元素缺少 name 属性,但似乎并非如此。

HTML代码:

<form class="testForm" action="/database" method="put">
            <input type="text" name="bar" value="foo">
</form>
<button type="button" class="testButt" name="testButt">click me!</button>

JS代码:

const testButt = document.querySelector('.testButt');
const testForm = document.querySelector(".testForm");

putDataTest = function(){

    var xhr = new XMLHttpRequest();
    var formData = new FormData(testForm);
    console.log(formData);      // using existing form as a source, returns an empty formData object;
    formData.append("foo", "bar");
    console.log(formData);      // populating the object explicitly, still empty formData object;
    xhr.open('PUT', '/database');
    xhr.send(formData);         // server sees req.body as empty
}

testButt.addEventListener("click", putDataTest);

尝试

console.log(document.forms[0].bar.value); // gets value from textbox.

创建您自己的表单数据:

var formData = new FormData();     // this is a *new* FormData object.
formData.append('foo', 'bar');
console.log(formData.get('foo'));

数据其实是有的,但是你不能通过console.log(formData)输出对象直接访问值。参见 How to inspect FormData?. You can also output specific values by using the get() 方法。

举个例子:

const testButt = document.querySelector('.testButt');
const testForm = document.querySelector(".testForm");

putDataTest = function() {

  var xhr = new XMLHttpRequest();
  var formData = new FormData(testForm);
  formData.append("new", "foo");
  console.log(formData.get('new'));
  for (var pair of formData.entries()) {
    console.log(pair[0] + ', ' + pair[1]);
  }
  xhr.open('PUT', '/database');
  xhr.send(formData); // server sees req.body as empty
}

testButt.addEventListener("click", putDataTest);
<form class="testForm" action="/database" method="put">
  <input type="text" name="foo" value="bar">
  <input type="text" name="bar" value="foo">
</form>
<button type="button" class="testButt" name="testButt">click me!</button>