XMLHttpRequest已经被弃用,应该使用什么替代它?

13
尝试使用纯JS方法检查我是否具有有效的JS图像URL。我收到一个警告,提示XMLHttpRequest已被弃用。有更好的方法吗?
尝试使用纯JS方法检查我是否具有有效的JS图像URL。我收到一个警告,提示XMLHttpRequest已被弃用。有更好的方法吗?
urlExists(url) {
    const http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    if (http.status !== 404) {
      return true;
    }
    return false;
  }

你在哪个环境/浏览器中收到了警告? - Chris Tavares
2
请阅读您收到的完整警告。 - Dekel
这是异步XMLHttpRequest的最简单用法。https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests - bodomalo
4个回答

15

你可能会收到这样一条消息,提示XMLHttpRequest的同步使用被弃用了(因为它对用户体验有害,会在等待响应时冻结页面)。我可以向您保证,该API的正确异步使用方式并没有被弃用。

以下是正确使用的示例代码:

var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
    if (this.readyState === this.DONE) {
        console.log(this.status) // do something; the request has completed
    }
}
xhr.open("HEAD", "http://example.com") // replace with URL of your choosing
xhr.send()


3

2

警告很可能是因为你正在尝试进行同步请求。


0

XMLHttpRequest已被弃用,因为自2015年起,Fetch API取代了它的位置。官方在2023年正式弃用。

await fetch(url, {
    method: "POST", // GET, POST, PUT, DELETE
    mode: "cors", // no-cors, cors, same-origin
    cache: "no-cache", // default, no-cache, reload, force-cache, only-if-cached
    credentials: "same-origin", // include, same-origin, omit
    headers: {
      "Content-Type": "application/json",
      // 'Content-Type': 'application/x-www-form-urlencoded',
    }, extra options);

如果某些东西被弃用了,Mozilla会找到特定于HTTP相关领域的替代方法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接