Как получить код состояния HTTP с помощью jQuery? - PullRequest
62 голосов
/ 02 июня 2010

Я хочу проверить, возвращает ли страница код состояния 401. Возможно ли это?

Вот моя попытка, но она возвращает только 0.

$.ajax({
    url: "http://my-ip/test/test.php",
    data: {},
    complete: function(xhr, statusText){
    alert(xhr.status); 
    }
});

Ответы [ 7 ]

89 голосов
/ 27 сентября 2012

это возможно с помощью метода 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');
   },
});
60 голосов
/ 13 августа 2013

Третий аргумент - это объект 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
});
20 голосов
/ 02 июня 2010

Воспользуйтесь ошибкой обратного вызова.

Например:

jQuery.ajax({'url': '/this_is_not_found', data: {}, error: function(xhr, status) {
    alert(xhr.status); }
});

Оповестит 404

7 голосов
/ 05 июня 2015

Я нашел это решение, где вы можете просто, проверьте код ответа сервера, используя код состояния .

Пример:

$.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);
} 
});
7 голосов
/ 02 июня 2010

Я думаю, вам также следует реализовать функцию ошибок метода $. Ajax .

ошибка (XMLHttpRequest, textStatus, errorThrown) Функция

Функция, которая будет вызвана, если запрос выходит из строя. Функция передана три аргументы: объект 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); 
    }
});
6 голосов
/ 02 июня 2010
$.ajax({
    url: "http://my-ip/test/test.php",
    data: {},
    error: function(xhr, statusText, errorThrown){alert(xhr.status);}
});
3 голосов
/ 13 июля 2018

Я инкапсулирую jQuery Ajax в метод:

var http_util = function (type, url, params, success_handler, error_handler, base_url) {

    if(base_url) {
        url = base_url + url;
    }

    var success = arguments[3]?arguments[3]:function(){};
    var error = arguments[4]?arguments[4]:function(){};



    $.ajax({
        type: type,
        url: url,
        dataType: 'json',
        data: params,
        success: function (data, textStatus, xhr) {

            if(textStatus === 'success'){
                success(xhr.code, data);   // there returns the status code
            }
        },
        error: function (xhr, error_text, statusText) {

            error(xhr.code, xhr);  // there returns the status code
        }
    })

}

Использование:

http_util('get', 'http://localhost:8000/user/list/', null, function (status_code, data) {
    console(status_code, data)
}, function(status_code, err){
    console(status_code, err)
})
...