封装 jQuery.ajax
2019-08-24 本文已影响0人
独钓寒江月
封装一个 jQuery.ajax
window.jQuery.ajax = function(url, method, body, success, fail){
let request = new XMLHttpRequest()
request.open(method, url)
request.onreadystatechange = ()=>{
if(request.readyState === 4){
if(request.status >= 200 && request.status < 300){
success.call(undefined, request.responseText)
}else if(request.status >= 400){
fail.call(undefined, request)
}
}
}
request.send(body)
}
升级jQuery.ajax 满足 Promise 规则
window.jQuery.ajax = function({url, method, body}){
return new Promise(function(resolve, reject){
let request = new XMLHttpRequest()
request.open(method, url)
request.onreadystatechange = ()=>{
if(request.readyState === 4){
if(request.status >= 200 && request.status < 300){
resolve.call(undefined, request.responseText)
}else if(request.status >= 400){
reject.call(undefined, request)
}
}
}
request.send(body)
})
}