HTTP HEAD Request in Javascript/Ajax?

Is it possible to do a HTTP Head request solely using an XMLHTTPRequest in JavaScript?

My motivation is to conserve bandwidth.

If not, is it possible to fake it?

Answers


Easy, just use the HEAD method, instead of GET or POST:

function UrlExists(url, callback)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url);
    http.onreadystatechange = function() {
        if (this.readyState == this.DONE) {
            callback(this.status != 404);
        }
    };
    http.send();
}

This is just a short example to show how to use the HEAD method. Production code may need more fine-grained callbacks for different result states (success, failure, timeout), and may use different event handlers (onload, onerror and ontimeout rather than onreadystatechange).


Need Your Help

WriteOnly Property or Method?

.net coding-style

Is there a particular scenario where a WriteOnly property makes more sense then a method? The method approach feels much more natural to me.

Objective-C: Mutating parameters

ios objective-c cocoa-touch

Is it safe to have a method edit a parameter and not be inside a category.