XMLHttpRequest 已弃用.用什么代替?

问题描述:

尝试使用纯 JS 方法来检查我是否有有效的 JS 图像 url.我收到一个警告,指出 XMLHttpRequest 已被弃用.有什么更好的方法可以做到这一点?

Trying to use a pure JS approach to check if I have a valid JS image url. I am getting a warning that XMLHttpRequest is deprecated. What is a better way to do this?

urlExists(url) {
    const http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    if (http.status !== 404) {
      return true;
    }
    return false;
  }

您可能会收到一条消息,即 XMLHttpRequest 的同步使用已被弃用(因为它对用户体验有不利影响;它在等待响应时冻结页面).我可以向您保证,该 API 的正确异步使用不会被弃用.

You're probably getting a message that the synchronous use of XMLHttpRequest is deprecated (because of its harmful effect on the user experience; it freezes the page while waiting for a response). I can assure you that proper asynchronous use of that API is not deprecated whatsoever.

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

Here's some example code for the correct use:

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