两种写法:
onreadystatechange
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data.json', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
//也可以写作 xhr.readyState === 4
console.log(xhr.responseText);
}
};
xhr.send();
onload
const xhr = new XMLHttpRequest()
xhr.addEventListener('load', () => {
if(xhr.status === 200){
console.log(JSON.parse(xhr.responseText))
}
})
xhr.open('GET', 'https://api.example.com/data.json')
xhr.send()
}
onload 等价于 readyState === 4