views:

53

answers:

1

This question has been posted on Stack before, but none so specific as to what I'm trying to understand.

The simplest way to check if a URL is corrrect to send a http Head request. But how do you use that to specify the URL ?

I found this in a previous post :

function UrlExists(url) {
  var http = new XMLHttpRequest();
  http.open('HEAD', url, false);
  http.send();
  return http.status!=404;
}

But it doesn't seem to run in firebug for a few reasons.

My apologies ahead of time for being daft.

+4  A: 

I'd recommend to use jQuery for correct cross-browser ajax requests:

function UrlExists(url, cb){
    jQuery.ajax({
        url:      url,
        dataType: 'text',
        type:     'GET',
        complete:  function(xhr){
            if(typeof cb === 'function')
               cb.apply(this, [xhr.status]);
        }
    });
}

Usage:

UrlExists('/path/script.pl', function(status){
    if(status === 200){
       // file was found
    }
    else if(status === 404){
       // 404 not found
    }
});
jAndy
+1, but wouldn't you want to check for status codes other than 200 and 404? It could be a 500 or 304, etc
Neil N
Is your if statement in your complete missing a `{}` ?
Trip
@Neil: indeed, it should be extended to check for more status codes. @Trip: no, you can do one statement without `{}`
jAndy