HTTP HEAD Request in Javascript/Ajax?

2019-01-01 07:26发布

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?

2条回答
何处买醉
2楼-- · 2019-01-01 07:46

An XMLHTTPRequest object should have

getAllResponseHeaders();
getResponseHeader("header-name")

defined on it

查看更多
零度萤火
3楼-- · 2019-01-01 07:54

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).

查看更多
登录 后发表回答