[jquery] jQuery : $ .ajax.error 메서드 내에서 HTTP 상태 코드를 얻는 방법은 무엇입니까?

AJAX 요청을 만들기 위해 jQuery를 사용하고 있습니다. HTTP 상태 코드가 400 오류인지 500 오류인지에 관계없이 다른 작업을 수행하고 싶습니다. 어떻게하면 되나요?

$.ajax({
    type: 'POST',
    url: '/controller/action',
    data: $form.serialize(),
    success: function(data){
        alert('horray! 200 status code!');
    },
    error: function(data){
        //get the status code
        if (code == 400) {
            alert('400 status code! user error');
        }
        if (code == 500) {
            alert('500 status code! server error');
        }
    },
});

최신 정보:

@GeorgeCummins는 응답 본문으로 작업하는 것이 “이상하게 보였습니다”라고 언급했습니다. 이런 일을 시도한 것은 이번이 처음입니다. 내 접근 방식이 모범 사례가 아닙니까? 무엇을 추천하나요? 여기에 또 다른 StackOverflow 질문을 만들었습니다 . 사용자 / 양식 유효성 검사 오류가있을 때 AJAX 요청에 어떤 응답 / 상태 코드를 보내야합니까?



답변

jQuery 1.5를 사용하는 경우 statusCode작동합니다.

jQuery 1.4를 사용하는 경우 다음을 시도하십시오.

error: function(jqXHR, textStatus, errorThrown) {
    alert(jqXHR.status);
    alert(textStatus);
    alert(errorThrown);
}

첫 번째 경고의 상태 코드가 표시되어야합니다.


답변

다음 statusCode설정을 사용하여 작업 맵을 만들어야 합니다.

$.ajax({
  statusCode: {
    400: function() {
      alert('400 status code! user error');
    },
    500: function() {
      alert('500 status code! server error');
    }
  }
});

참조 (스크롤 : ‘statusCode’)

편집 (댓글에 대한 응답으로)

응답 본문에 반환 된 데이터를 기반으로 조치를 취해야하는 경우 (이상하게 보임) error:대신 사용해야 합니다.statusCode:

error:function (xhr, ajaxOptions, thrownError){
    switch (xhr.status) {
        case 404:
             // Take action, referencing xhr.responseText as needed.
    }
}


답변

다른 해결책은 response.status 함수를 사용하는 것입니다. 이것은 ajax 호출에 의해 반환되는 http 상태를 제공합니다.

function checkHttpStatus(url) {
    $.ajax({
        type: "GET",
        data: {},
        url: url,
        error: function(response) {
            alert(url + " returns a " + response.status);
        }, success() {
            alert(url + " Good link");
        }
    });
}


답변

사용하다

   statusCode: {
    404: function() {
      alert('page not found');
    }
  }

$.ajax({
    type: 'POST',
    url: '/controller/action',
    data: $form.serialize(),
    success: function(data){
        alert('horray! 200 status code!');
    },
    statusCode: {
    404: function() {
      alert('page not found');
    },

    400: function() {
       alert('bad request');
   }
  }

});


답변