배너 이미지

Form의 데이터 전달하기

최종 수정일 : (11개월 전)

xhr(XMLHttpRequest) 혹은 fetch 등으로 데이터를 보낼(POST) 때, 쓰는 스크립트입니다.

input[type="submit"]을 클릭했을 때와 같은 동작을 하는 버튼을 만들 때 쓰신다고 생각하시면 편합니다.

function serialize(form) {
    const serialized = new FormData();

    for (let i = 0length = form.elements.lengthi < lengthi++) {
        const field = form.elements[i];
        
        if (field.name && !field.disabled && "file" !== field.type && "reset" !== field.type && "submit" !== field.type && "button" !== field.type) {

            if ("select-multiple" === field.type) {
                for (let n = 0n < field.options.lengthn++)
                    field.options[n].selected && serialized.append(field.namefield.options[n].value);
            }

            else {
                ("checkbox" !== field.type && "radio" !== field.type || field.checked&& serialized.append(field.namefield.value)
            }

        }
        
    }

    return serialized;
}

위 함수를 추가한 뒤

* jQuery엔 .serialize()란 함수가 있습니다. 참고

const myForm = document.getElementById("myForm");
const data = serialize(myForm);

fetch(myForm.action, {
  method"POST",
  bodydata
})

이런 방식으로 데이터를 보내시면 됩니다.

예시에선 form에 적힌 action의 url로 데이터를 보냈는데, myForm.action을 "https://example.com"등 주소로 변경하실 수도 있습니다.


profile

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

주의 : 비밀 댓글 사용 시 수정 기능을 이용할 수 있는 시간이 지나면 작성자도 내용 확인이 불가능합니다.