Get All Items from HTML5 FormData Object - HTML5

徘徊边缘 提交于 2019-12-05 10:04:18

All the functions for FormData aren't available in all browsers by default. However, you can enable them in some. Checkout the docs for browser compatibility.

In Chrome, you'll be able to enable full access to these functions by enabling Enable experimental Web Platform feature under the browser flags section. Navigate to chrome://flags/ in the browser to find this option.

Once you've enable this feature and reloaded, you should be able to run the following to view all your FormData, data:

var formData    = new FormData(this);
var formKeys    = formData.keys();
var formEntries = formData.entries();

do {
  console.log(formEntries.next().value);
} while (!formKeys.next().done)

Granted, there are probably better ways to iterate over this data structure, although it is certainly one way to view all the K/V pairs in your FormData object dynamically.

I don't see how you can't know the keys of your FormData object.

In the case of new FormData(HTMLFormElement), the name of each input field will be used as a key name.

In other cases, you do set it, so you can store it if you need.

var form = document.forms.namedItem("fileinfo");
form.addEventListener('submit', function(ev) {
  ev.preventDefault();
  var oOutput = document.querySelector("div"),
    oData = new FormData(form);
  var file = oData.get('yourFile')
  oOutput.innerHTML = file.name + '  ' + file.size + ' bytes';
}, false);
<form enctype="multipart/form-data" method="post" name="fileinfo">
  <label>Your email address:</label>
  <input type="email" autocomplete="on" autofocus name="userid" placeholder="email" size="32" maxlength="64" />
  <br />
  <label>File to stash:</label>
  <input type="file" name="yourFile" required />
  <input type="submit" value="Stash the file!" />
</form>
<div></div>

According to the specs, only input tags with a name attribute are submitted to the server, so if this name attribute is missing, you won't find it in the FormData either.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!