从jQuery AJAX读取HTTP状态/错误代码的问题

我正在尝试正确处理可能由jQuery中的任何AJAX调用返回的HTTP状态错误(404,501等)(我使用的是1.6.4版)但是对于我的生活我无法脱身适当的响应代码(所有值都是’0’或’错误’,没有更具体的)。

更新:在这里创建了一个JSFIDDLE

更新:添加statusCode: { *** }根据3nigma的建议但不会触发

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

我得到的输出如下:

控制台输出

仅供参考我在…研究了文档

http://api.jquery.com/jQuery.ajax/ (“错误(jqXHR,textStatus,errorThrown)”部分) http://api.jquery.com/jQuery.ajax/#jqXHR

但是jqXHR似乎没有正确填充。 我一定做错了,现在我的想法已经用完,所以我真的很感激一些帮助。 谢谢!

尝试使用jquery 1.5中添加的statusCode

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

我是一个numpty,出于安全原因,ajax不能跨域工作。 如果我更改url以使其定位与主机相同的域,则会奇迹般地填充状态代码和文本等。

我在这里添加了另一个JSFIDDLE示例来演示这个。