问题描述
是否有可能只用一个XMLHTT prequest在JavaScript做一个HTTP请求头?
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?
推荐答案
非常容易,只要用它代替GET或POST HEAD方法,:
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();
}
这只是一个小例子来说明如何使用HEAD方法。生产code可能需要更细粒度的回调不同的结果状态(成功,失败,超时),并且可以使用不同的(的onload
,的onerror
和 ontimeout
,而不是的onreadystatechange
)。
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
).
这篇关于在Javascript / Ajax的HTTP HEAD请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!