jQuery $ .ajax,error handling程序不起作用

您好我注意到这个简单的代码不能正常运行…

function test() { $.ajax( { 'url' : 'test/GameConfiguration.json', 'dataType' : 'json', data : { a : 'aaa' }, cache : false, method : 'get', timeout : 10000, //10 secs of timeout success : function(data, textStatus, XMLHttpRequest) { console.log("success"); if (data == null) console.log("it's not a real success"); }, error : function(XMLHttpRequest, textStatus, errorThrown) { console.log("error: " + textStatus); } }); } 

测试已在localhost上运行,我的意思是:我加载页面,关闭本地网络服务器,然后我发出请求(通过一个简单的按钮,onclick指向此function)。 错误永远不会被调用,我得到的是调用成功处理程序,它有textStatus =“success”和data = null。 我甚至注意到请求在10秒之前很久就会超时。 这种情况发生在Firefox(最新版本),Chrome(最新版本)和Safari 5上。为什么会这样? 是因为我正在使用localhost吗?


我忘了告诉:请求没有缓存。 实际上,firebug和Chrome开发工具都会显示失败请求。


大更新

此行为与localhost的使用有关。 事实上,如果我从另一个同事PC加载此页面并在触发请求之前我将我的PC与网络断开连接,我正确地将error handling程序以超时作为状态触发。 我认为这是jQuery的一个bug。 这将使我很难测试超时错误:(


来自jQuery论坛的人说这是由于网络堆栈中断连接的方式,因为主机是localhost。 我只在Windows 7上测试过这个。 如果你想在其他系统上测试这个并且你可以编写一些jQuery内部,请在jQuery论坛上报告这篇文章:

http://forum.jquery.com/topic/strange-and-unexpected-behaviour-of-ajax-error-and-localhost#14737000001331961

更新 :尝试将测试(data == null)替换为(XMLHttpRequest.readyState === 4 && XMLHttpRequest.status === 0)

在W3C Candidate关于XMLHttpRequest标准的建议XMLHttpRequest描述了它必须存在如此命名的“错误标志”,它应该用于指示某种类型的网络错误或流产。 在出现这种错误的情况下, XMLHttpRequest的状态将为0而不是200(“OK”),201(“Created”),304(“Not Modified”)等等。 要完全对应于http://www.w3.org/TR/XMLHttpRequest/#the-status-attribute,XMLHttpRequest.status在XMLHttpRequest.status等于0或1(“UNSENT”或“OPENED”的情况下可以为0 “)。 另一种情况是XMLHttpRequest.readyState等于4(“DONE”)和“错误标志”为真。 如果我们在这两种情况下没有,则XMLHttpRequest.status必须是HTTP状态代码。 在http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html或http://www.w3.org/Protocols/HTTP/1.0/spec.html#Status-Codes下没有HTTP状态代码等于0.所以在我看来,你可以做到以下

 jQuery(document).ready(function () { $.ajax({ type: 'GET', url: 'test/GameConfiguration.json', dataType: 'json', cache : false, success: function(data, textStatus, xhr){ if (xhr.readyState === 4 && xhr.status === 0) { // if readyState is DONE (numeric value 4) then corresponds to // http://www.w3.org/TR/XMLHttpRequest/#dom-xmlhttprequest-done // "The DONE state has an associated error flag that indicates // some type of network error or abortion." // Corresponds to http://www.w3.org/TR/XMLHttpRequest/#the-status-attribute // If error flag it true, xhr.status is 0. alert('"error flag\" is true. It means that we have a network error"+ " or abortion (for example because of Same Origin Policy restrictions)'); } else { alert(textStatus); alert(data); } }, error: function(xhr, textStatus, errorThrown) { if (textStatus !== null) { alert("error: " + textStatus); } else if (errorThrown !== null) { alert("exception: " + errorThrown.message); } else { alert ("error"); } } }); }); 

如果出现网络错误,将调用success回调而不是error即使它没有多大意义。 查看此博客文章了解详细信息。 所以基本上你通过检查data == null做的是正确的。

即使您关闭本地服务器,它仍然应该能够看到json文件..尝试暂时删除该文件,看看是否有效。