How to inspect FormData?

旧城冷巷雨未停 提交于 2019-11-25 23:14:23

问题


I\'ve tried console.log and looping through it using for in.

Here it the MDN Reference on FormData.

Both attempts are in this fiddle.

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);
}

How can I inspect form data to see what keys have been set.


回答1:


Updated Method:

As of March 2016, recent versions of Chrome and Firefox now support using FormData.entries() to inspect FormData. Source.

// Create a test FormData object
var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');

// Display the key/value pairs
for (var pair of formData.entries()) {
    console.log(pair[0]+ ', ' + pair[1]); 
}

Thanks to Ghost Echo and rloth for pointing this out!

Old Answer:

After looking at these Mozilla articles, it looks like there is no way to get data out of a FormData object. You can only use them for building FormData to send via an AJAX request.

I also just found this question that states the same thing: FormData.append("key", "value") is not working.

One way around this would be to build up a regular dictionary and then convert it to FormData:

var myFormData = {
    key1: 300,
    key2: 'hello world'
};

var fd = new FormData();
for (var key in myFormData) {
    console.log(key, myFormData[key]);
    fd.append(key, myFormData[key]);
}

If you want to debug a plain FormData object, you could also send it in order to examine it in the network request console:

var xhr = new XMLHttpRequest;
xhr.open('POST', '/', true);
xhr.send(fd);



回答2:


Short answer

console.log(...fd)

Longer answer

If you would like to inspect what the raw body would look like then you could use the Response constructor (part of fetch API)

var fd = new FormData

fd.append("key1", "value1")
fd.append("key2", "value2")

new Response(fd).text().then(console.log)

Some of wish suggest logging each entry of entries, but the console.log can also take multiple arguments
console.log(foo, bar)
To take any number of argument you could use the apply method and call it as such: console.log.apply(console, array).
But there is a new ES6 way to apply arguments with spread operator and iterator
console.log(...array).

Knowing this, And the fact that FormData and both array's has a Symbol.iterator method in it's prototype you could just simply do this without having to loop over it, or calling .entries() to get the the hold of iterator

var fd = new FormData

fd.append("key1", "value1")
fd.append("key2", "value2")

console.log(...fd)



回答3:


I use the formData.entries() method. I'm not sure about all browser support, but it works fine on Firefox.

Taken from https://developer.mozilla.org/en-US/docs/Web/API/FormData/entries

// Create a test FormData object
var formData = new FormData();
formData.append('key1','value1');
formData.append('key2','value2');

// Display the key/value pairs
for (var pair of formData.entries())
{
 console.log(pair[0]+ ', '+ pair[1]); 
}

There is also formData.get() and formData.getAll() with wider browser support, but they only bring up the Values and not the Key. See the link for more info.




回答4:


In certain cases, the use of :

for(var pair of formData.entries(){... 

is impossible.

I've used this code in replacement :

var outputLog = {}, iterator = myFormData.entries(), end = false;
while(end == false) {
   var item = iterator.next();
   if(item.value!=undefined) {
       outputLog[item.value[0]] = item.value[1];
   } else if(item.done==true) {
       end = true;
   }
    }
console.log(outputLog);

It's not a very smart code, but it works...

Hope it's help.




回答5:


ES6+ solutions:

To see the structure of form data:

console.log([...formData])

To see each key-value pair:

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



回答6:


When I am working on Angular 5+ (with TypeScript 2.4.2), I tried as follows and it works except a static checking error but also for(var pair of formData.entries()) is not working.

formData.forEach((value,key) => {
      console.log(key+" "+value)
});

var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');

formData.forEach((value,key) => {
  console.log(key+" "+value)
});

Check at Stackblitz




回答7:


Here's a function to log entries of a FormData object to the console as an object.

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);
};

MDN doc on .entries()

MDN doc on .next() and .done




回答8:


  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) {


            },

       });
}



回答9:


You have to understand that FormData::entries() returns an instance of Iterator.

Take this example form:

<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>

and this JS-loop:

<script>
    var it = new FormData( document.getElementById('form-id') ).entries();
    var current = {};
    while ( ! current.done ) {
        current = it.next();
        console.info( current )
    }
</script>



回答10:


In angular 7 i got entries on console using below line of code.

formData.forEach(entries => console.log(entries));



回答11:


Already answered but if you want to retrieve values in an easy way from a submitted form you can use the spread operator combined with creating a new Map iterable to get a nice structure.

new Map([...new FormData(form)])




回答12:


Try this function:

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



回答13:


Easy Method

I used this code in angular 7

var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');

 formData.forEach((value,key) => {
    console.log(key+value)
     });```




回答14:


in typeScript of angular 6, this code is working for me.

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

or for all values:

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



回答15:


The MDN suggests the following form:

let formData = new FormData();
formData.append('name', 'Alex Johnson')
for(let keyValuePair of formData.entries()){
    console.log(keyValuePair); //has form ['name','Alex Johnson']
}

Alternatively

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

Consider adding ES+ Polyfills, in case the browser or environment doesn't support latest JavaScript and FormData API.

I hope this helps.



来源:https://stackoverflow.com/questions/17066875/how-to-inspect-formdata

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