如何检查javascript中是否存在文件? [英] How to check if a file exists in javascript?

查看:125
本文介绍了如何检查javascript中是否存在文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

$(#Main").load("login.html")

$("#Main").load("login.html")

如果文件(在本例中为'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?

推荐答案

您可以使用ajaxComplete事件,从而可以访问xhr对象,您可以查询请求的状态,例如,状态404表示文件不存在.

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.

文档 http://docs.jquery.com/Ajax/ajaxComplete#callback中的更多信息

在此处测试 http://pastebin.me/48f32a74927bb

例如

$("#someDivId").ajaxComplete(function(request, settings){
    if (settings.status===404){
        //redirect here
    }
});

这篇关于如何检查javascript中是否存在文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆