[3일차] Ajax

저요·2022년 9월 25일

2022 100th day challenge

목록 보기
3/97

서론

Ajax로 파일 업로드를 진행하는 동안 로딩바를 띄우고자 했는데 문제가 있었다.
완전히 일치하지는 않지만 문제의 코드를 러프하게 재현해 보았다.

button.click("clickButton();");

function clickButton(){
  $.ajax({
    dataType: dataForm,
    type : post,
    url: url,
    data: data,
    beforeSend : function(data, status, xhr){
      //실행전
      $("#loading").show;
    },
    success: function(data, status, xhr){
      //성공
      $("#loading").hide;
    },
    error : function(data, status, xhr){
      //에러
      $("#loading").hide;
    },
    complete : function(data, status, xhr){
      //완료
      $("#loading").hide;
    }
  });
};

찾으면서 알게 된 지식인데 dataType은 통신의 결과로 넘어올 데이터 타입을 결정하는 것이었고 contentType은 서버로 보내는 데이터 타입을 지정하는 것이었다.
이런식으로 실행하기 전에 로딩바를 화면에서 띄우고 실행이 끝나 성공, 에러, 완료 되었을때 로딩바가 사라지도록 기대하며 구현을 했다. 하지만 내가 원하는 대로 로딩바가 띄워지지 않았다.

본론

과연 무엇이 문제였을까?
다른것에 손을 대지 않고 hide를 제거했을 때 loading이 띄워진 뒤에 사라지지 않았다.
show가 완전히 작동하지 않는건 아니었다.

이 문제는 다음과 같은 방법으로 해결했다.

button.click(
	$("#loading").show;
	
	setTimeOut(()=>{
		clickButton();
    },0);
);

function clickButton(){
  $.ajax({
    dataType: dataForm,
    type : post,
    url: url,
    data: data,
    beforeSend : function(data, status, xhr){
      //실행전
    },
    success: function(data, status, xhr){
      //성공
      $("#loading").hide;
    },
    error : function(data, status, xhr){
      //에러
      $("#loading").hide;
    },
    complete : function(data, status, xhr){
      //완료
      $("#loading").hide;
    }
  });
};

마무리

이 문제에 대한 정확한 해결에 대해서는 다음주에 말하고자 한다.
내일은 ajax의 기본 구조와 문법에 대해서 좀 더 자세히 설명하고 싶다.

profile
웹개발

0개의 댓글