I'm using the jquery library to load the content of an html file. Something like this:
我正在使用jquery库来加载html文件的内容。像这样的东西:
$("#Main").load("login.html")
If the file (in this case 'login.html') does not exist, I would like to detect it so that I can redirect the user to an error page for example. Any ideas how I can detect if the file to load exists or not?
如果文件(在这种情况下是'login.html')不存在,我想检测它,以便我可以将用户重定向到错误页面。任何想法我如何检测是否存在要加载的文件?
2 个解决方案
#1
12
You can use the ajaxComplete event, whis gives you access to the xhr object which you can query the status of the request e.g a status of 404 will mean the file does not exist.
你可以使用ajaxComplete事件,你可以访问xhr对象,你可以查询请求的状态,例如404的状态意味着该文件不存在。
More Info in the docs http://docs.jquery.com/Ajax/ajaxComplete#callback
更多信息,请参阅文档http://docs.jquery.com/Ajax/ajaxComplete#callback
Test here http://pastebin.me/48f32a74927bb
在这里测试http://pastebin.me/48f32a74927bb
e.g
$("#someDivId").ajaxComplete(function(request, settings){
if (settings.status===404){
//redirect here
}
});
#2
1
@PConroy's solution works, but it does the same thing for all failed ajax requests.
@ PConroy的解决方案可行,但它对所有失败的ajax请求都做同样的事情。
If you need this on a per request basis - i.e. if the first request fails it goes to X page and if the second fails go to Y, then you need to do this using the error handle in the $.ajax function:
如果你需要基于每个请求 - 即如果第一个请求失败则转到X页面,如果第二个失败则转到Y,那么你需要使用$ .ajax函数中的错误句柄来执行此操作:
(to edit: http://jsbin.com/iwume/edit)
(编辑:http://jsbin.com/iwume/edit)
#1
12
You can use the ajaxComplete event, whis gives you access to the xhr object which you can query the status of the request e.g a status of 404 will mean the file does not exist.
你可以使用ajaxComplete事件,你可以访问xhr对象,你可以查询请求的状态,例如404的状态意味着该文件不存在。
More Info in the docs http://docs.jquery.com/Ajax/ajaxComplete#callback
更多信息,请参阅文档http://docs.jquery.com/Ajax/ajaxComplete#callback
Test here http://pastebin.me/48f32a74927bb
在这里测试http://pastebin.me/48f32a74927bb
e.g
$("#someDivId").ajaxComplete(function(request, settings){
if (settings.status===404){
//redirect here
}
});
#2
1
@PConroy's solution works, but it does the same thing for all failed ajax requests.
@ PConroy的解决方案可行,但它对所有失败的ajax请求都做同样的事情。
If you need this on a per request basis - i.e. if the first request fails it goes to X page and if the second fails go to Y, then you need to do this using the error handle in the $.ajax function:
如果你需要基于每个请求 - 即如果第一个请求失败则转到X页面,如果第二个失败则转到Y,那么你需要使用$ .ajax函数中的错误句柄来执行此操作:
(to edit: http://jsbin.com/iwume/edit)
(编辑:http://jsbin.com/iwume/edit)