How do I get the HTTP status code with jQuery?

前端 未结 9 1447
逝去的感伤
逝去的感伤 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条回答
  • 2020-11-27 14:12

    this is possible with jQuery $.ajax() method

    $.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');
       },
    });
    
    0 讨论(0)
  • 2020-11-27 14:12

    Test in WAMP SERVER apache2

    abrir el httpd.conf y agregar esto:

    <IfModule mod_headers.c>
      Header set Access-Control-Allow-Origin "*"
    </IfModule>
    

    enable the next module on apache headers_module

    restart all services

    0 讨论(0)
  • 2020-11-27 14:14

    Use the error callback.

    For example:

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

    Will alert 404

    0 讨论(0)
  • 2020-11-27 14:16
    $.ajax({
        url: "http://my-ip/test/test.php",
        data: {},
        error: function(xhr, statusText, errorThrown){alert(xhr.status);}
    });
    
    0 讨论(0)
  • 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)
    })
    
    0 讨论(0)
  • 2020-11-27 14:23

    I have had major issues with ajax + jQuery v3 getting both the response status code and data from JSON APIs. jQuery.ajax only decodes JSON data if the status is a successful one, and it also swaps around the ordering of the callback parameters depending on the status code. Ugghhh.

    The best way to combat this is to call the .always chain method and do a bit of cleaning up. Here is my code.

    $.ajax({
            ...
        }).always(function(data, textStatus, xhr) {
            var responseCode = null;
            if (textStatus === "error") {
                // data variable is actually xhr
                responseCode = data.status;
                if (data.responseText) {
                    try {
                        data = JSON.parse(data.responseText);
                    } catch (e) {
                        // Ignore
                    }
                }
            } else {
                responseCode = xhr.status;
            }
    
            console.log("Response code", responseCode);
            console.log("JSON Data", data);
        });
    
    0 讨论(0)
提交回复
热议问题