var xhr = new XMLHttpRequest()
xhr.open('get', url, true)
xhr.send()
xhr.onreadystatuschange = function() {
if (xhr.readyStatus === 4) {
if(xhr.status === 200) {
success(xhr.responseText)
} else {
fail && fail(xhr.status)
}
}
}
进阶 - promise方式的ajax
function ajax(url) {
return new Promise(function(reslove, reject) {
const xhr = new XMLHttpRequest() xhr.open('GET', url)
xhr.onload = function() {
if (this.status === 200) {
reselove(this.response)
}
reject(new Error(this.statusText))
}
})
}