Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
579 views
in Technique[技术] by (71.8m points)

jquery - How to check if a file exists in javascript?

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

$("#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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

More Info in the docs http://docs.jquery.com/Ajax/ajaxComplete#callback

Test here http://pastebin.me/48f32a74927bb

e.g

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...