Problems Reading the HTTP Status/Error Code from jQuery AJAX

对着背影说爱祢 提交于 2019-12-11 06:25:24

问题


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.



来源:https://stackoverflow.com/questions/7685288/problems-reading-the-http-status-error-code-from-jquery-ajax

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!