Appearance
异步
javascript
const xhr = new XMLHttpRequest()
xhr.open('GET', './index.json')
xhr.onreadystatechange = function () {
console.log(xhr.readyState) // 2 3 4
}
xhr.send(null)同步
javascript
const xhr = new XMLHttpRequest()
xhr.open('GET', './index.json', false)
xhr.onreadystatechange = function () {
console.log(xhr.readyState) // 4
}
xhr.send(null) // 同步任务,当状态码变为 4 时这行代码才执行完。
const xhr = new XMLHttpRequest()
xhr.open('GET', './index.json', false)
xhr.send(null)
// 此时状态码已经变为 4
// 回调不会执行,因为状态码不会再改变了。
xhr.onreadystatechange = function () {
console.log(xhr.readyState)
}