How do I get the HTTP status code with jQuery?

前端 未结 9 1679
逝去的感伤
逝去的感伤 2020-11-27 13:34

I want to check if a page returns the status code 401. Is this possible?

Here is my try, but it only returns 0.

$.ajax({
    url: \"http://my-ip/tes         


        
9条回答
  •  旧时难觅i
    2020-11-27 14:17

    I encapsulate the jQuery Ajax to a method:

    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
            }
        })
    
    }
    

    Usage:

    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)
    })
    

提交回复
热议问题