Problems Reading the HTTP Status/Error Code from j

2019-08-12 22:50发布

问题:

I'm trying to appropriately handle a HTTP status error (404, 501, etc) that might be returned by any AJAX call in jQuery (I'm using version 1.6.4) however for the life of me I can't get out the appropriate response code (all values are '0' or 'error' and nothing more specific).

UPDATE: created a JSFIDDLE here

UPDATE: added statusCode: { *** } as per 3nigma's suggestion BUT which does not fire

<!DOCTYPE html><html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
    <script type="text/javascript">
        function doAjax()
        {
            $.ajax({
                type: "GET",
                url: "http://www.non-existant-url.com/",
                success: function(data, textStatus, jqXHR){
                    alert("Success");
                },
                error: function (xhr, textStatus, errorThrown) {
                     console.log("xhr.status: " + xhr.status);
                     console.log("xhr.statusText: " + xhr.statusText);
                     console.log("xhr.readyState: " + xhr.readyState);
                     console.log("xhr.responseText: " + xhr.responseText);
                     console.log("xhr.responseXML: " + xhr.responseXML);
                     console.log("textStatus: " + textStatus);
                     console.log("errorThrown: " + errorThrown);
                     console.log("xhr.redirect: " + xhr.redirect);
                        },
                statusCode: {
                    404: function () { console.log("404"); },
                    501: function () { console.log("501"); },
                    502: function () { console.log("502"); }
                }
            });
        }
    </script>
</head>
<body><button onclick="doAjax();">Do AJAX</button></body>
</html>

The output I get is as follows:

FYI I've studied the documentation at...

http://api.jquery.com/jQuery.ajax/ (the "error(jqXHR, textStatus, errorThrown)" section) http://api.jquery.com/jQuery.ajax/#jqXHR

but the jqXHR doesn't seem to be populating properly. I must be doing something wrong and I've run out of ideas now so I would really appreciate some help. Thanks!

回答1:

try using statusCode added in jquery 1.5

$.ajax({
  ...
  statusCode: {
    502: function() {
      alert('502');
    }
  }
});


回答2:

I'm a numpty, ajax doesn't work cross-domain for security reasons. If I change the url so that its targetting the same domain as the host then the status codes and text etc is miraculously populated.

I've added another JSFIDDLE example to demonstrate this here.