XMLHttpRequest is deprecated. What to use instead?

前端 未结 3 693
没有蜡笔的小新
没有蜡笔的小新 2021-02-08 18:14

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?

3条回答
  •  遥遥无期
    2021-02-08 18:34

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

提交回复
热议问题