我已经尝试了console.log和循环通过它使用for in。

这里是关于FormData的MDN参考。

两种尝试都在这把小提琴上。

var fd = new FormData(),
    key;

// poulate with dummy data
fd.append("key1", "alskdjflasj");
fd.append("key2", "alskdjflasj");

// does not do anything useful
console.log(fd);

// does not do anything useful   
for(key in fd) {
    console.log(key);
}

如何检查表单数据以查看已设置的键。


当前回答

下面是一个将FormData对象的条目作为对象记录到控制台的函数。

export const logFormData = (formData) => {
    const entries = formData.entries();
    const result = {};
    let next;
    let pair;
    while ((next = entries.next()) && next.done === false) {
        pair = next.value;
        result[pair[0]] = pair[1];
    }
    console.log(result);
};

.entries()上的MDN文档

MDN文档。next()和。done

其他回答

你必须理解FormData::entries()返回一个Iterator实例。

以这个表单为例:

<form name="test" id="form-id">
    <label for="name">Name</label>
    <input name="name" id="name" type="text">
    <label for="pass">Password</label>
    <input name="pass" id="pass" type="text">
</form>

和这个js循环:

<script>
    var it = new FormData( document.getElementById('form-id') ).entries();
    var current = {};
    while ( ! current.done ) {
        current = it.next();
        console.info( current )
    }
</script>
  function abc(){ 
    var form = $('#form_name')[0]; 
        var formData = new FormData(form);
        for (var [key, value] of formData.entries()) { 
            console.log(key, value);
        }
        $.ajax({
            type: "POST",
            url: " ",
            data:  formData,
            contentType: false,
            cache: false,
            processData:false,
            beforeSend: function() {

            },
            success: function(data) {


            },

       });
}

在angular 6的typeScript中,这段代码为我工作。

var formData = new FormData();
formData.append('name', 'value1');
formData.append('name', 'value2');
console.log(formData.get('name')); // this is return first element value.

或者对于所有值:

console.log(formData.getAll('name')); // return all values

ES6 +方案:

要查看表单数据的结构:

console.log([...formData])

要查看每个键-值对:

for (let [key, value] of formData.entries()) {
  console.log(`${key}: ${value}`);
}

试试这个函数:

function formDataToObject(formData) {
  return Array.from(formData.entries()).reduce((old, pair) => ({
    ...old,
    [pair[0]]: pair[1],
  }), {});
}