jQuery 如何检查文件是否存在于javascript中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/197228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 08:45:47  来源:igfitidea点击:

How to check if a file exists in javascript?

jqueryfileexists

提问by Anthony

I'm using the jquery library to load the content of an html file. Something like this:

我正在使用 jquery 库加载 html 文件的内容。像这样的东西:

$("#Main").load("login.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”)不存在,我想检测它,以便我可以将用户重定向到错误页面。任何想法如何检测要加载的文件是否存在?

回答by redsquare

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

回答by Remy Sharp

@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 函数中的错误句柄执行此操作:

http://jsbin.com/iwume

http://jsbin.com/iwume

(to edit: http://jsbin.com/iwume/edit)

(编辑:http: //jsbin.com/iwume/edit