Programing

FormData를 검사하는 방법?

lottogame 2020. 5. 22. 08:06
반응형

FormData를 검사하는 방법?


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

양식 데이터를 검사하여 어떤 키가 설정되어 있는지 확인할 수 있습니다.


업데이트 된 방법 :

2016 년 3 월 현재 최신 버전의 Chrome 및 Firefox는 이제 FormData.entries()FormData 검사를 지원 합니다. 소스 .

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

이것을 지적 해 주신 Ghost Echorloth 에게 감사드립니다 !

기존 답변 :

Mozilla 기사를 살펴본 후 FormData 객체에서 데이터를 가져올 수있는 방법이없는 것 같습니다. AJAX 요청을 통해 전송할 FormData를 빌드하는 데만 사용할 수 있습니다.

나는 또한 같은 질문을하는이 질문을 발견했다 : FormData.append ( "key", "value") is not working .

이 문제를 해결하는 한 가지 방법은 일반 사전을 작성한 다음이를 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]);
}

일반 FormData 오브젝트를 디버그하려는 경우 네트워크 요청 콘솔에서 검사하기 위해 전송할 수도 있습니다.

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

나는 formData.entries()방법을 사용한다 . 모든 브라우저 지원에 대해 잘 모르겠지만 Firefox에서는 제대로 작동합니다.

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

이 또한 formData.get()formData.getAll()넓은 브라우저를 지원하지만, 단지 값이 아닌 키를 가지고. 자세한 내용은 링크를 참조하십시오.


짧은 답변

console.log(...fd)

더 긴 답변

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)


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.


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


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

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


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


            },

       });
}

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>

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

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

Try this function:

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

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


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

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.

참고URL : https://stackoverflow.com/questions/17066875/how-to-inspect-formdata

반응형