Javascript/Ajax 中的 HTTP HEAD 请求?

发布于 2024-07-09 12:15:17 字数 105 浏览 6 评论 0原文

是否可以仅使用 JavaScript 中的 XMLHTTPRequest 来执行 HTTP Head 请求?

我的动机是节省带宽。

如果不是,是否可以造假?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

情绪少女 2024-07-16 12:15:17

很简单,只需使用 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();
}

这只是一个简短的示例,展示如何使用 HEAD 方法。 生产代码可能需要针对不同结果状态(成功、失败、超时)进行更细粒度的回调,并且可能使用不同的 事件处理程序onloadonerrorontimeout 而不是 onreadystatechange)。

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

金兰素衣 2024-07-16 12:15:17

更现代的方法是使用 Fetch API 替换XMLHttpRequest

例如(在async函数内)

const url = "https://example.com";
const response = await fetch(url, { method: "HEAD" });
console.log(`Got status: ${response.status}`);

The more modern approach is to use the Fetch API which replaced XMLHttpRequest.

e.g. (within an async function)

const url = "https://example.com";
const response = await fetch(url, { method: "HEAD" });
console.log(`Got status: ${response.status}`);

櫻之舞 2024-07-16 12:15:17

XMLHTTPRequest 对象

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

应该在其上定义

An XMLHTTPRequest object should have

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

defined on it

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文