jQuery: $.ajax.error 메서드 내에서 HTTP 상태 코드를 가져오는 방법은 무엇입니까?
JQuery를 사용하여 AJAX 요청을 하고 있습니다.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');
}
},
});
업데이트:
@George Cummins는 대응 기관과 일하는 것이 "이상해 보였다"고 언급했습니다.제가 이런 일을 시도한 것은 이번이 처음입니다.내 접근 방식이 모범 사례가 아닌가요?무엇을 추천하시겠습니까?여기에 대해 다른 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')
EDIT(댓글에 대한 답변)
응답 본문에 반환된 데이터를 기반으로 작업을 수행해야 하는 경우(이상하게 생각됨),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');
}
}
});
여기서 당신도 이것을 사용할 수 있습니다. 그것은 저에게 효과가 있습니다.
$.ajax({
success: function(data, textStatus, xhr) {
console.log(xhr.status);
},
complete: function(xhr, textStatus) {
console.log(xhr.status);
}
});
언급URL : https://stackoverflow.com/questions/6700822/jquery-how-to-get-the-http-status-code-from-within-the-ajax-error-method
'programing' 카테고리의 다른 글
스크롤로 인해 응답 테이블 내부의 부트스트랩 버튼 드롭다운이 표시되지 않음 (0) | 2023.08.15 |
---|---|
PHP SOAP Client Class에서 생성된 실제 XML을 보려면 어떻게 해야 합니까? (0) | 2023.08.15 |
원인: 빌드Output.apkData는 null일 수 없습니다. (0) | 2023.08.15 |
100% CPU를 사용하는 W3WP.EXE - 어디서부터 시작해야 합니까? (0) | 2023.08.15 |
Excel VBA - 코드에서 셀 값 읽기 (0) | 2023.08.15 |