Is it possible to do a HTTP Head request solely using an XMLHTTPRequest in JavaScript?
是否可以仅使用JavaScript中的XMLHTTPRequest来执行HTTP Head请求?
My motivation is to conserve bandwidth.
我的动机是节省带宽。
If not, is it possible to fake it?
如果不是,有可能伪造吗?
2 个解决方案
#1
86
Easy, just use the HEAD method, instead of GET or POST:
简单,只需使用HEAD方法,而不是GET或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
).
这只是一个简短的示例,演示如何使用HEAD方法。生产代码可能需要对不同的结果状态(成功、失败、超时)进行更细粒度的回调,并且可能使用不同的事件处理程序(onload、onerror和ontimeout,而不是onreadystatechange)。
#2
2
An XMLHTTPRequest object should have
XMLHTTPRequest对象应该有
getAllResponseHeaders();
getResponseHeader("header-name")
defined on it
上定义它
#1
86
Easy, just use the HEAD method, instead of GET or POST:
简单,只需使用HEAD方法,而不是GET或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
).
这只是一个简短的示例,演示如何使用HEAD方法。生产代码可能需要对不同的结果状态(成功、失败、超时)进行更细粒度的回调,并且可能使用不同的事件处理程序(onload、onerror和ontimeout,而不是onreadystatechange)。
#2
2
An XMLHTTPRequest object should have
XMLHTTPRequest对象应该有
getAllResponseHeaders();
getResponseHeader("header-name")
defined on it
上定义它