메뉴 건너뛰기

2021.03.25 16:15

ajax 동기화 처리하기

조회 수 416 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

동기화가 필요한 코드

아래의 코드는 ajax를 통해 로그인 여부 확인 후 로그인이 안된 경우 dwg 확장명을 가진 파일이 다운로드 안되도록 하는 코드이다. 실제 다운로드시 서버 단에서 한번 더 체크하는 부분은 별도로 있다.

 

수정전

아래처럼 작성한 경우 비동기 처리되어 로그인 여부 확인이 뒤늦게 이루어져서 "다운로드 권한이 없습니다." 라는 메시지가 의도한 대로 잘 작동되지 않는다.

 


/**
 * 로그온 여부 확인
 * @returns {Boolean}
 */
function isLogon() {
    //데이터 요청
    $.ajax({
        url : contextPath+'/main/isLogon.ajax',
        type : 'POST',
        dataType : 'json',
        contentType : 'application/json; charset=UTF-8',
        success : function(result) {
            //console.log("result : "+JSON.stringify(result));
            //console.log("basicInfoList : "+result.basicInfoList.length);
            return result;
        },
        error : function(request,status,error) {
            console.log("code:"+request.status+"\n\n"+ "message:" + request.responseText + "\n\n"+"error:"+error);
            //alert($(request.responseText.replace(/(\r\n|\n|\r)/gm,"")).text());
            //alert("처리에 실패하였습니다.\ncode:"+request.status+"\n"+"error:"+error);
        },
        complete : function() {
        }
    });
}

$(document).ready(function() {
    /**
     * 파일 다운로드 처리
     */
    $(document).on('click', '.down', function(){
        //로그인 시에만 다운로드 처리
        var ext = ($(this).text().split("."));
        //로그인 여부와 확장자 확인하는 부분
        if (isLogon() == false && ext[ext.length-1].toLowerCase() == "dwg") {
            //로그인이 안되었고 확장자가 dwg라면
            alert("다운로드 권한이 없습니다.");
        } else {
            var fileSn = $(this).data("filesn");
            var seq = $(this).data("seq");
            window.open(contextPath+"/main/filedown.do?seq="+seq+"&fileSn="+fileSn);
        }
    });
});

 

그래서 $.ajax(); 의 async 속성 사용으로 뭔가 방법을 찾을수 있을까 생각 했지만 async는 deprecated 되었다고 한다. async : false로 설정시 아래의 오류가 발생하였다.

파이어폭스에서... 메인 쓰레드에서의 동기화된 XMLHttpRequest는 사용자 경험에 안좋은 영향을 미치기 때문에 더이상 사용하지 않습니다. 더 자세한 사항은 http://xhr.spec.whatwg.org/ 를 참고해 주십시오.

크롬에서... [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

 

수정후

이번엔 조금 다른 병식을 찾아서 적용해 보았다. 이번엔 의도한 대로 작동이 잘 되었다.

 


/**
 * 로그온 여부 확인
 * @returns {Boolean}
 */
function isLogon() {
    //데이터 요청
    var pormise = $.ajax({
        url : contextPath+'/main/isLogon.ajax',
        type : 'POST',
        //data : JSON.stringify(data),
        //async : false, //deprecated
        dataType : 'json',
        contentType : 'application/json; charset=UTF-8',
        success : function(result) {
            //console.log("result : "+JSON.stringify(result));
            //console.log("basicInfoList : "+result.basicInfoList.length);
        },
        error : function(request,status,error) {
            //console.log("code:" + request.status+"\n\n" + "message:" + request.responseText + "\n\n"+"error:"+error);
            //alert($(request.responseText.replace(/(\r\n|\n|\r)/gm,"")).text());
            //alert("처리에 실패하였습니다.\ncode:"+request.status+"\n"+"error:"+error);
        },
        complete : function() {
        }
    });
 
    return pormise;
}

$(document).ready(function() {
    /**
     * 파일 다운로드 처리
     */
    $(document).on('click', '.down', function(){
        var ext = ($(this).text().split("."));
        var fileSn = $(this).data("filesn");
        var seq = $(this).data("seq");
        var pormise = isLogon();
        var sessionOn = false;

        //jqXHR.done(function( data, textStatus, jqXHR ) {});
        //jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
        //jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { });
        
        pormise.done(function(result){
            sessionOn = result;
            //console.log(result);
         
            //로그인 여부와 확장자 확인하는 부분
            if (sessionOn == false && ext[ext.length-1].toLowerCase() == "dwg") {
                //로그인이 안되었고 확장자가 dwg라면
                alert("다운로드 권한이 없습니다.");
            } else {
                window.open(contextPath+"/main/filedown.do?seq=" + seq + "&fileSn=" + fileSn);
            }
        });
        //pomise.fail(function(){ ... }); //아직 테스트 못해봄
        //pomise.always(function(){ ... }); //아직 테스트 못해봄
    });
});
 

  1. fadeIn() , fadeOut() 을 이용한 간단한 자동 그림 전환

    Date2021.03.26 Views285
    Read More
  2. 기본 동작 막기

    Date2021.03.25 Views287
    Read More
  3. jQuery - 드래그앤드롭(DragAndDrop)을 통한 파일 업로드

    Date2021.03.09 Views291
    Read More
  4. click에 따른 마우스 휠 on off

    Date2021.03.31 Views304
    Read More
  5. javascript, jQuery에서 루프 돌리기 예 (for, forEach, each)

    Date2021.03.25 Views311
    Read More
  6. 다중 select

    Date2021.03.31 Views316
    Read More
  7. 최초 접속시 css와 script가 로딩되지 않을때

    Date2021.03.25 Views322
    Read More
  8. 목록의 체크 선택/해제에 따라 [전체선택] 체크박스를 체크하거나 해제하기

    Date2021.03.25 Views329
    Read More
  9. jQuery - 드래그, 리사이즈 이벤트에 따른 영역 침범 막기

    Date2021.03.09 Views363
    Read More
  10. Cesium에서 canvas 화면 center 지점의 좌표 취득

    Date2021.03.25 Views373
    Read More
  11. ajax 동기화 처리하기

    Date2021.03.25 Views416
    Read More
  12. jQuery - radio, checkBox값 가져오기, 선택하기, 제어 등

    Date2021.03.09 Views543
    Read More
  13. SELECTBOX MULTIPLE 검색하기

    Date2021.03.26 Views572
    Read More
  14. jQuery - 클릭이벤트 동적 처리하기($("").click(), on('click') 차이)

    Date2021.03.09 Views580
    Read More
  15. 간단한 마우스 포인터 따라 다니기

    Date2021.03.26 Views594
    Read More
  16. jQuery - ajax xhr을 활용한 파일 업로드 진행 상태 확인하기

    Date2021.03.09 Views598
    Read More
  17. jQuery - checkbox 전체 선택, 해제 기능 및 단일 체크박스가 해제되었을때 전체 선택 해제 하기

    Date2021.03.09 Views613
    Read More
  18. 모달 띄우는 코드

    Date2021.03.25 Views657
    Read More
  19. JS 첵박스 샘플

    Date2019.06.04 Views694
    Read More
  20. 사업자 번호를 입력하면 자동으로 하이픈을 붙여줍니다.

    Date2020.08.24 Views704
    Read More
Board Pagination Prev 1 2 3 4 5 6 7 8 9 Next
/ 9

하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved