티스토리 뷰

javascript

ajaxForm&ajaxSubmit

개몽구리 2017. 12. 30. 18:21

ajax를 더욱 쉽게 사용할 수 있도록 해주는 플러그인 (AjaxForm.js)


게시판을 ajaxForm 을 이용하여 디비에 등록,수정,삭제 성공여부에 따라 페이지 이동을 다르게 적용하면서 문제가 발생


 function insertAjax(){
		var url;
		 $("[name='writeForm']").ajaxForm({
			ayncs : true,
			cash  : false,
			type  : "post",
			url   : "/webBoardAjax/BoardAction",
			dataType : "JSON",
			success : function(data){
				console.log(data);
				if(data.error=="Y"){
					alert("실패하였습니다.");
				}else{
					alert("성공하였습니다.");
					url = "http://localhost:8181/webBoardAjax/BoardAction";
				}
			},
			error : function(xhr, status, error){
				console.log("error");
			},
			complete : function(event,request,settings){
				console.log("완료");
				if(url){
					$(location).attr("href",url);
				}
			}
		}).submit(); 
	}

위 처럼 일반 글 등록 시에는 메인으로 이동만 하면 됨으로 location.href를 이용하여 페이지 이동을 하면 상관없었지만,   


    function updateAjax(){
        var result;
         $("[name='writeForm']").ajaxForm({
            ayncs : true,
            cash  : false,
            type  : "post",
            url   : "/webBoardAjax/BoardAction",
            dataType : "JSON",
            success : function(data){
                console.log(data);
                if(data.error=="Y"){
                    alert("실패하였습니다.");
                }else{
                    alert("성공하였습니다.");
                    result = true;
                }
            },
            error : function(xhr, status, error){
                console.log("error");
            },
            complete : function(event,request,settings){
                console.log("완료");
                 if(result){
                    $("[name='cmd']").val("list");
                    $("[name='writeForm']").removeAttr("enctype");
                    $("[name='writeForm']").submit(); /*submit 시 ajaxForm이 실행*/
                }
            }
        }).submit();
    }

이처럼 글 수정이나 삭제 시에 직전에 검색한 검색 명이나 선택되었던 페이지 번호를 form을 통해 메인에 가지고 가야하는 경우 폼의 action 값이나 주소값 변경 후 form.submit 으로 폼을 전송하면 폼이 전송되는 것이 아니라 ajaxForm이 실행된다.


문제는 ajaxForm을 실행 시 <처음 실행 시에는 updateAjax() 함수 호출전이므로 form에 submit이벤트가 등록되기 전> ajaxForm 을 통해 해당 폼에 $("form").on("submit",ajaxForm) 과 같은 형태의 이벤트가 등록되어버리기 때문에

이후에 해당 form에 submit() 이벤트가 일어나면  ajaxForm이 실행되는 것으로 이해된다.


이는 ajaxForm.js에 명시되었는데,

	/*
		Usage Note:
		-----------
		Do not use both ajaxSubmit and ajaxForm on the same form. These
		functions are mutually exclusive. Use ajaxSubmit if you want
		to bind your own submit handler to the form. For example,
		$(document).ready(function() {
			$('#myForm').on('submit', function(e) {
				e.preventDefault(); // <-- important
				$(this).ajaxSubmit({
					target: '#output'
				});
			});
		});
		Use ajaxForm when you want the plugin to manage all the event binding
		for you. For example,
		$(document).ready(function() {
			$('#myForm').ajaxForm({
				target: '#output'
			});
		});
		You can also use ajaxForm with delegation (requires jQuery v1.7+), so the
		form does not have to exist when you invoke ajaxForm:
		$('#myForm').ajaxForm({
			delegation: true,
			target: '#output'
		});
		When using ajaxForm, the ajaxSubmit function will be invoked for you
		at the appropriate time.
	*/

플러그인이 모든 이벤트(전송)를 핸들러하려면 ajaxForm을 사용하라고 하고 있으며,  내부적으로는 ajaxForm이 ajaxSubmit을

실행시키고있기때문에 그 둘을 혼용하여 사용하지 말도록 권장하고 있다. 또한 필요한 경우 ajaxSubmit 을 직접적으로 사용하도록 하고 있는데 ajaxSubmit을 사용하여 실행시에는 그 전과 같은 모든 submit이벤트를 핸들러 하지 않는 것으로 이해된다.


따라서 다음과 같이 ajaxForm을 ajaxSubmit으로 수정하여 ajax사용시 문제가 해결되었다.


function updateAjax(){
		var result;
		 $("[name='writeForm']").ajaxSubmit({
			ayncs : true,
			cash  : false,
			type  : "post",
			url   : "/webBoardAjax/BoardAction",
			dataType : "JSON",
			success : function(data){
				console.log(data);
				if(data.error=="Y"){
					alert("실패하였습니다.");
				}else{
					alert("성공하였습니다.");
					result = true;
				}
			},
			error : function(xhr, status, error){
				console.log("error");
			},
			complete : function(event,request,settings){
				console.log("완료");
				 if(result){	
					$("[name='cmd']").val("list");
					$("[name='writeForm']").removeAttr("enctype");
					$("[name='writeForm']").submit();	
				} 
			}
		}).submit(); 
	}


이 방법 외에 ajaxForm 플러그인에서

해당 폼에 ajaxForm 이벤트를 unbind 시켜주는 함수가 존재하기 때문에 아래와 같이 ajaxFormUnbind() 함수를 사용하여 해당 form에 걸린 submit 이벤트를 해제하고 전송을 하는 방법이 있다.


function updateAjax(){
		var result;
		 $("[name='writeForm']").ajaxForm({
			ayncs : true,
			cash  : false,
			type  : "post",
			url   : "/webBoardAjax/BoardAction",
			dataType : "JSON",
			success : function(data){
				console.log(data);
				if(data.error=="Y"){
					alert("실패하였습니다.");
				}else{
					alert("성공하였습니다.");
					result = true;
				}
			},
			error : function(xhr, status, error){
				console.log("error");
			},
			complete : function(event,request,settings){
				console.log("완료");
				 if(result){
					$("[name='writeForm']").ajaxFormUnbind();		
					$("[name='cmd']").val("list");
					$("[name='writeForm']").removeAttr("enctype");
					$("[name='writeForm']").submit();	
				} 
			}
		}).submit(); 
	}


ajaxFormUnbind()


	// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
	$.fn.ajaxFormUnbind = function() {
		return this.off('submit.form-plugin click.form-plugin');
	};


'javascript' 카테고리의 다른 글

onload & DOMContentLoaded (양재동코드랩)  (0) 2017.12.16
참조타입외  (0) 2017.03.13
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함