0

Is there an easy way to script a function based off a file existing or not in a particular folder? Perhaps running a 404 test against the folder?

For example:

If default.html exists in child directory preview, then do this ... else do this ...?

Thanks for any help.

  • http://stackoverflow.com/questions/3646914/how-do-i-check-if-file-exists-in-jquery-or-javascript – ngray Apr 17 '13 at 23:34

1 Answers1

0

You could do something like this:

function exists(url) {
    var request = $.ajax({
        type: 'HEAD',
        async: false,
        url: url
    });

    return request.status === 200;
}

I wouldn't use this, however. It's a blocking call and will momentarily lock up the browser. Use the error callback of the ajax function and make the request asynchronous:

$.ajax({
    type: 'HEAD',
    url: url
}).fail(function(request, status, error) {
    // Error
}).done(function(data, status, request) {
    // Success
});

Better yet, don't do this at all.

Blender
  • 289,723
  • 53
  • 439
  • 496