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
'Develop' 카테고리의 다른 글
로그 파일에서 특정 문자열 찾기 cat, more 및 기타 명령어 활용법 (1) | 2025.02.24 |
---|---|
[Javascript] html javascript 로 엑셀 다운로드 구현. 총정리 (1) | 2025.02.21 |
Spring Framework의 Scheduled 스케줄 동적으로 실행 방법 (4) | 2025.02.17 |
리눅스 서버 시간 확인하는 다양한 방법 (1) | 2025.02.14 |
Open Graph(OG) 프로토콜이란? 사용방법까지 총정리 (0) | 2025.02.13 |