Develop

[JavaScript] ajax post 요청 form 내용 json 으로 전송

issuemaker99 2025. 2. 21. 14:30
728x90

jQuery의 $.ajax() 또는 fetch()를 사용해서 POST 요청을 보낼 수 있어.
FormData를 JSON 형식으로 변환해서 보내는 방식으로 설명할게.

✅ jQuery $.ajax()를 사용하는 방법

$(document).ready(function () {
    $("#submitBtn").click(function () {
        // form 데이터 가져오기
        let formData = $("#myForm").serializeArray();
        let jsonData = {};

        // FormData를 JSON 객체로 변환
        $.each(formData, function () {
            jsonData[this.name] = this.value;
        });

        // AJAX 요청
        $.ajax({
            url: "/your-endpoint",  // 요청을 보낼 URL
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify(jsonData), // JSON 데이터로 변환
            success: function (response) {
                console.log("성공:", response);
            },
            error: function (xhr, status, error) {
                console.error("에러:", error);
            }
        });
    });
});

 

  • serializeArray()  form 데이터를 배열 형태로 가져옴
  • JSON.stringify(jsonData) → JSON 문자열로 변환
  • contentType: "application/json" → 서버에서 JSON으로 인식하게 설정

 fetch()를 사용하는 방법 (Vanilla JS)

document.getElementById("submitBtn").addEventListener("click", function () {
    let formElement = document.getElementById("myForm");
    let formData = new FormData(formElement);
    let jsonData = {};

    // FormData를 JSON 형식으로 변환
    formData.forEach((value, key) => {
        jsonData[key] = value;
    });

    fetch("/your-endpoint", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(jsonData)
    })
    .then(response => response.json())
    .then(data => console.log("성공:", data))
    .catch(error => console.error("에러:", error));
});

 


📌 HTML 폼 예제

<form id="myForm">
    <input type="text" name="username" placeholder="이름">
    <input type="email" name="email" placeholder="이메일">
    <button type="button" id="submitBtn">전송</button>
</form>
LIST