我试图正确处理可能由jQuery中的任何AJAX调用返回的HTTP状态错误(404,501等)(我正在使用1.6版本。 4)但是对于我的生活,我无法得到适当的响应代码(所有的值都是'0'或'错误',没有更具体的)。从jQuery中读取HTTP状态/错误代码的问题AJAX
UPDATE:创建的jsfiddle here
更新:加入statusCode: { *** }
按3nigma的建议,但其中不火
<!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>
我得到的输出如下:
仅供参考我已经学习了文档...
http://api.jquery.com/jQuery.ajax/(以下简称 “错误(jqXHR,textStatus,errorThrown)” 一节) http://api.jquery.com/jQuery.ajax/#jqXHR
但jqXHR似乎并没有得到适当的填充。我一定在做错事,现在我已经没有想法了,所以我非常感谢一些帮助。谢谢!
感谢您的回复。我试过这个,但函数没有被调用。我会更新我的原始帖子以反映您的建议。 –
这是在jQuery 1.6中实现的。要检查您的jQuery版本,您可以使用:http://stackoverflow.com/a/6867073/1042999 The Documentation:http://api.jquery.com/jquery.ajax/ –