How to inspect FormData?

前端 未结 15 1305
悲&欢浪女
悲&欢浪女 2020-11-22 08: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 fi

相关标签:
15条回答
  • 2020-11-22 08:25

    Easy Method

    I used this code in angular 8

    var formData = new FormData();
    formData.append('key1', 'value1');
    formData.append('key2', 'value2');
    
     formData.forEach((value,key) => {
        console.log(key+value)
         });
    
    
    0 讨论(0)
  • 2020-11-22 08:27

    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
    
    0 讨论(0)
  • 2020-11-22 08:27

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

    formData.forEach(entries => console.log(entries));
    
    0 讨论(0)
  • 2020-11-22 08:31

    Try this function:

    function formDataToObject(formData) {
      return Array.from(formData.entries()).reduce((old, pair) => ({
        ...old,
        [pair[0]]: pair[1],
      }), {});
    }
    
    0 讨论(0)
  • 2020-11-22 08:32

    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

    0 讨论(0)
  • 2020-11-22 08:34

    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.

    0 讨论(0)
提交回复
热议问题