스프링 부트

[SpringBoot] ajax - html form tag 로 요청하기!

h__hj 2022. 8. 13. 23:15

# jQuery Ajax(form tag) <> Spring Boot

html form tag 를 이용하여 ajax 통신하기!

# 환경

/**
 * tool: STS 4.13.0
 * version: 2.7.3-SNAPSHOT
 * java: 1.8
 * type: MAVEN
 * view: THYMELEAF
 * jQuery: 3.6.0
 */

# page

# html (일부분 발췌)

<h3>form element submit</h3>
<form id="formSend">
    <input type="text" name="text" placeholder="Text" style="display: inline;" required/>
    <br>
    <input type="text" name="html" placeholder="Html" style="display: inline;" value="<div>Hello World<div>"/>
    <br>
    <input type="text" name="script" placeholder="Script" style="display: inline;" value="<script>function test() { alert('hello world!');}</script>"/>
    <br>
    <input type="submit" id="form1" value="jsonView" name="json" style="display: inline;"/>
    <input type="submit" id="form2" value="ResponseBody" name="body" style="display: inline;"/>
</form>
<br>

# function (일부분 발췌)

const test = {
    form: function(type) {
        sendForm(`/test/send/${type}`, $('#formSend'),
            function(result) {
                console.log(result.text);
                console.log(result.html);
                console.log(result.script);
            }
        );
    },
}

$(document).ready(function() {
    $('#formSend').on('submit', function(event) {
        event.preventDefault();
			
        const type = event.originalEvent.submitter.id;   // form1, form2
        const name = event.originalEvent.submitter.name; // json, body
        test.form(type);
    });	
});

# jQuery ajax (일부분 발췌)

function sendForm(url, formEl, cbSuccess) {
    $.ajax({
        // options
            url         : url,
            method      : "POST",
            data        : $(formEl).serialize(),
            dataType    : "json", 
            beforeSend  : function(jqXHR, settings) {
                // throw '에러';
                // return false;
            }
        // success
        }).done(function(output, textStatus, jqXHR) {
            if(typeof cbSuccess === 'function') {
                cbSuccess(output);
            }
        // error	
        }).fail(function(jqXHR) {
            console.log("ERROR");
        // complete
        }).always(function(output, textStatus, jqXH) {
            console.log("COMPLETE");
        }
    );
}

# @Controller (일부분 발췌)

@Slf4j
@Controller
@RequestMapping("/test/send")
public class TestSendController {

	@PostMapping("/form1")
	public ModelAndView form1(ModelAndView mav, @ModelAttribute TestSendPVO testSendPVO) {
		log.debug("[PARAMETER] {}", testSendPVO);
		
		mav.setStatus(HttpStatus.OK);
		mav.setViewName("jsonView");
		
		mav.addObject("text", testSendPVO.getText());
		mav.addObject("html", testSendPVO.getHtml());
		mav.addObject("script", testSendPVO.getScript());
		return mav;
	}
	
	@PostMapping("/form2")
	public @ResponseBody TestSendPVO form2(@ModelAttribute TestSendPVO testSendPVO) {
		log.debug("[PARAMETER] {}", testSendPVO);
		return testSendPVO;
	}
}

# 내용

 html 에서 form 태그로 ajax 통신을 할 때 중요한 부분이 몇가지 있다.

  1. 해당 form 태그의 submit 기본 이벤트 정지.
    • event.preventDefault() 를 이용하여 submit의 기본동작을 금지시킨다.
  2. 특정 버튼 감지
    • form 태그 안에 submit 버튼이 여러개라면 event.originalEvent.submitter 를 이용하여 무슨 버튼인지 구분한다.
  3. parameter setting
    • form 태그의 serialize() 를 이용하여 파라미터를 만들어준다.
    • key1=value1&key2=value2 형태로 만들어줌. 
    • 한글일 경우 encodeURIComponent() 처리 됨.

# ajax 요청 방식에 따른 파라미터 맵핑 방법.

https://hjho95.tistory.com/14 ajax settings
https://hjho95.tistory.com/7 application/x-www-form-urlencoded
https://hjho95.tistory.com/8 application/json
https://hjho95.tistory.com/9 form tag
https://hjho95.tistory.com/10 multipart/form-data
https://hjho95.tistory.com/12 PUT, PATCH, DELETE
https://hjho95.tistory.com/11 POST 방식으로 PUT, PATCH, DELETE 사용하기

# ajax 시리즈의 참조 페이지.

preventDefault: https://developer.mozilla.org/ko/docs/Web/API/Event/preventDefault
serialize: https://api.jquery.com/serialize