To test what happens when I try to load a non-existent resource (on the same host as my web server), I set up the following code:
为了测试当我尝试加载一个不存在的资源(与我的web服务器相同的主机)时发生了什么,我设置了以下代码:
var wrongURL = "http://foo/bar.json"; // non-existent resource
$.ajax({
url: wrongURL,
dataType: 'json',
success: function(jsonResponse, textStatus, jqXHR) {
$.('#divOfInterest').html("you should never see this");
},
error: function(jqXHR, textStatus, errorThrown) {
$.('#divOfInterest').html("sorry, could not find URL");
}
});
// remainder of code...
Instead of seeing my div show the message sorry, could not find URL
, I get a console error:
没有看到我的div显示的信息对不起,找不到URL,我得到一个控制台错误:
GET http://foo/bar.json 404 (Not Found) - bar.json
Anything within the error
call and after the $.ajax()
block (i.e., // remainder of code
) does not get executed
在错误调用中以及$.ajax()块(例如。, // /代码的其余部分)不会被执行
It looks like my browser (Safari 5.1.5) is getting stuck on the 404 error and leaves the function early.
看起来我的浏览器(Safari 5.1.5)被404错误卡住了,并提前离开了这个功能。
How do I get to handle the error gracefully and execute the rest of my code?
如何优雅地处理错误并执行代码的其余部分?
2 个解决方案
#1
1
Just replace $.('#divOfInterest')
with $('#divOfInterest')
:D
只需用$('#divOfInterest')替换$.('#divOfInterest'):D。
Demo: http://jsfiddle.net/9Ua8J/
演示:http://jsfiddle.net/9Ua8J/
#2
2
From my understanding you need a server to actually return an error status for that error function to be run.
根据我的理解,您需要一个服务器来返回要运行的错误函数的错误状态。
For instance if you request a JSON object for a non existant user on Soundcloud, you will get a 404 error returned from the server.
例如,如果在Soundcloud上为不存在的用户请求一个JSON对象,服务器将返回404错误。
However of you mistype the full URI, then there is no resource returned at all, and no status code either.
但是,如果您将完整的URI打错了,那么就根本没有返回资源,也没有状态码。
#1
1
Just replace $.('#divOfInterest')
with $('#divOfInterest')
:D
只需用$('#divOfInterest')替换$.('#divOfInterest'):D。
Demo: http://jsfiddle.net/9Ua8J/
演示:http://jsfiddle.net/9Ua8J/
#2
2
From my understanding you need a server to actually return an error status for that error function to be run.
根据我的理解,您需要一个服务器来返回要运行的错误函数的错误状态。
For instance if you request a JSON object for a non existant user on Soundcloud, you will get a 404 error returned from the server.
例如,如果在Soundcloud上为不存在的用户请求一个JSON对象,服务器将返回404错误。
However of you mistype the full URI, then there is no resource returned at all, and no status code either.
但是,如果您将完整的URI打错了,那么就根本没有返回资源,也没有状态码。