Как получить код состояния HTTP с помощью jQuery?
Я хочу проверить, возвращает ли страница код состояния 401. Возможно ли это?
Вот моя попытка, но она возвращает 0.
$.ajax({
url: "http://my-ip/test/test.php",
data: {},
complete: function(xhr, statusText){
alert(xhr.status);
}
});
Ответы
Ответ 1
это возможно с помощью метода jQuery $.ajax()
$.ajax(serverUrl, {
type: OutageViewModel.Id() == 0 ? "POST" : "PUT",
data: dataToSave,
statusCode: {
200: function (response) {
alert('1');
AfterSavedAll();
},
201: function (response) {
alert('1');
AfterSavedAll();
},
400: function (response) {
alert('1');
bootbox.alert('<span style="color:Red;">Error While Saving Outage Entry Please Check</span>', function () { });
},
404: function (response) {
alert('1');
bootbox.alert('<span style="color:Red;">Error While Saving Outage Entry Please Check</span>', function () { });
}
}, success: function () {
alert('1');
},
});
Ответ 2
Третий аргумент - объект XMLHttpRequest, поэтому вы можете делать все, что хотите.
$.ajax({
url : 'http://example.com',
type : 'post',
data : 'a=b'
}).done(function(data, statusText, xhr){
var status = xhr.status; //200
var head = xhr.getAllResponseHeaders(); //Detail header info
});
Ответ 3
Используйте обратный вызов ошибки.
Например:
jQuery.ajax({'url': '/this_is_not_found', data: {}, error: function(xhr, status) {
alert(xhr.status); }
});
Будет предупреждать 404
Ответ 4
Я думаю, вы также должны реализовать функцию ошибки метода $. ajax.
error (XMLHttpRequest, textStatus, errorThrown) Функция
Функция, вызываемая, если запрос выходит из строя. Функция передается три arguments: объект XMLHttpRequest, строка, описывающая тип ошибки это произошло и объект исключения, если он произошел. Возможные значения для второго аргумент (кроме нуля) - это "тайм-аут", "ошибка", "немодифицировано" и "Parsererror".
$.ajax({
url: "http://my-ip/test/test.php",
data: {},
complete: function(xhr, statusText){
alert(xhr.status);
}
error: function(xhr, statusText, err){
alert("Error:" + xhr.status);
}
});
Ответ 5
$.ajax({
url: "http://my-ip/test/test.php",
data: {},
error: function(xhr, statusText, errorThrown){alert(xhr.status);}
});
Ответ 6
Я нашел это решение, где вы можете просто,
проверьте код ответа сервера, используя код состояния.
Пример:
$.ajax({
type : "POST",
url : "/package/callApi/createUser",
data : JSON.stringify(data),
contentType: "application/json; charset=UTF-8",
success: function (response) {
alert("Account created");
},
statusCode: {
403: function() {
// Only if your server returns a 403 status code can it come in this block. :-)
alert("Username already exist");
}
},
error: function (e) {
alert("Server error - " + e);
}
});