我已经尝试了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);
}

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


当前回答

你可以使用Array.from()

console.log(Array.from(formData.entries()))

其他回答

formData.entries()在最新版本中抛出错误。 所以你可以试试下面的方法:

formData.forEach((value: FormDataEntryValue, key: string) => {
      console.log(value, key);
    })

你必须理解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>

如果你正在使用typescript,那么你可以像这样控制FormData:

const productData = new FormData();
productData.append('name', name);
productData.append('description', description);
productData.forEach((key,value)=>{
   console.log(key, value)})

简短的回答

[...fd] // shortest devtool solution
Array.from(fd) // Same as above
console.log(...fd) // shortest script solution
console.log([...fd]) // Think 2D array makes it more readable
console.table([...fd]) // could use console.table if you like that
console.log(Object.fromEntries(fd)) // Works if all fields are uniq
console.table(Object.fromEntries(fd)) // another representation in table form
new Response(fd).text().then(console.log) // To see the entire raw body

再回答

其他人建议记录fd.entries()的每个条目,但是console.log也可以接受多个参数。要获取任意数量的参数,可以使用apply方法并像这样调用它:console.log。应用(控制台、数组)。 但是ES6有一种新的方法来应用扩展操作符和iteratorconsole.log(…array)参数。

知道这一点,事实上,FormData和数组都有一个符号。迭代器方法,该方法指定了…的循环,然后你可以用…展开参数iterable而不必去调用formData.entries()方法(因为这是默认函数),你可以只做(x of formData),如果你喜欢这样

var fd = new FormData() fd.append('key1', 'value1') fd.append('key2', 'value2') fd.append('key2', 'value3') // using it's default for...of specified by Symbol.iterator // Same as calling `fd.entries()` for (let [key, value] of fd) { console.log(`${key}: ${value}`) } // also using it's default for...of specified by Symbol.iterator console.log(...fd) // Only shows up in devtool (not here in this code snippet) console.table([...fd]) // Don't work in IE (use last pair if same key is used more) console.log(Object.fromEntries(fd))

如果你想检查原始的主体看起来像什么,然后你可以使用响应构造函数(获取API的一部分),这将转换你的表单数据,它实际上看起来像当你上传表单数据

var fd = new FormData() fd。追加(“key1”、“value1”) fd。追加(“key2”、“value2”) 新的响应(fd)。text () (console.log)

表单数据

var formData = new formData ();//当前为空 formData。追加(“用户名”,“克里斯”); for (formData.keys()的var键){ console.log(关键); } forformdata .values()的变量值{ console.log(价值); }

知道更多