I have been working with the HTML5 FormData object and I can't seem to figure out how to find what data it holds. I need to access it for debugging purposes.
https://developer.mozilla.org/en-US/docs/Web/API/FormData1
There are functions like
FormData::get([name]);
but I don't know the names. It would be nice to have something like the following:
FormData::dumpData();
What is a good way to view all of the data in a FormData object?
Update
Here is an example of the FormData object:
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.
来源:https://stackoverflow.com/questions/28906435/get-all-items-from-html5-formdata-object-html5