【问题标题】:Check url content type with javascript使用 javascript 检查 url 内容类型
【发布时间】:2014-07-25 20:26:19
【问题描述】:

为了节省服务器资源,我正在寻找一种方法来使用 javascript 检索给定 url 的内容类型。它不应该只从 url 下载标题的完整内容。这是否可能与 javascript 的限制有关。

【问题讨论】:

  • 我想你看过这个question?
  • 发出 HEAD 请求。多田!
  • 所以我认为外部 url 是不可能的
  • 不是不可能,这取决于服务器是否启用了CORS。

标签: javascript ajax http-headers content-type


【解决方案1】:

使用 head 请求进行 Ajax 调用。

var url = window.location.href;
var xhttp = new XMLHttpRequest();
xhttp.open('HEAD', url);
xhttp.onreadystatechange = function () {
    if (this.readyState == this.DONE) {
        console.log(this.status);
        console.log(this.getResponseHeader("Content-Type"));
    }
};
xhttp.send();

【讨论】:

  • 跨源网址怎么样?
  • @Exlord 如果他们确定有 COR,如果没有,让你的服务器端来做。
【解决方案2】:

仅供参考,如果您的服务器不允许 HEAD 请求但允许 GET 请求,您可以通过限制 GET 请求的范围来做到这一点。

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader("Range", "bytes=0");
xmlhttp.onreadystatechange = function () {
  if (this.readyState == this.DONE) {
    console.log(this.getResponseHeader("Content-Type"));
  }
};
xmlhttp.send();

【讨论】:

  • 这对我有用。另外,如果您想使用箭头函数而不是无名函数,请将“this”更改为“xmlhttp”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-28
  • 2015-03-13
  • 2013-09-16
  • 1970-01-01
  • 2021-05-26
  • 2011-04-11
  • 1970-01-01
相关资源
最近更新 更多