How to check if a file exists in javascript?

I am using the jquery library to load the contents of an html file. Something like that:

$ ("# 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 the error page, for example. Any ideas how I can determine if a file exists for download?

+3
source share
2 answers

You can use the ajaxComplete event, which gives you access to the xhr object, which you can request the status of the request, for example, 404 status will mean that 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
    }
});
+12

@PConroy , ajax.

- , , X, Y, , $.ajax:

http://jsbin.com/iwume

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

+1

Source: https://habr.com/ru/post/1698203/


All Articles