html代码:
js代码:
window.jQuery=function(){}
window.jQuery.ajax = function({method, url, body, headers, successFn, failFn}){ //ES6的解构赋值
let request = new XMLHttpRequest()
request.open(method, url)
request.onreadystatechange = function(){
if(request.readyState === 4){
if(request.status >=200 && request.status <300){
successFn.call(undefined, request.responseText)
}else if(request.status >= 400){
failFn.call(undefined, request)
}
}
}
request.send(body)
}
myButton.addEventListener('click',function(){
window.jQuery.ajax({
method: 'POST',
url: '/xxx',
body: 'a=1&&b=2',
headers: {
'content-type': 'x-www-form-urlencoded',
'frank': '18'
},
successFn:(responseText)=>{console.log("success")},
failFn:(request)=>{console.log("fail")}
})
})
使用上面这种方式有一个问题,成功和失败都有一个函数,这个函数名每次都需要另取,不规范。我们采用Promise就可以解决这个问题。
window.jQuery=function(){}
window.jQuery.ajax = function({method, url, body, headers, successFn, failFn}){
return new Promise(function(resolve, reject){
let request = new XMLHttpRequest()
request.open(method, url)
request.onreadystatechange = function(){
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)
})
}
myButton.addEventListener('click',function(){
window.jQuery.ajax({
method: 'POST',
url: '/xxx',
body: 'a=1&&b=2',
headers: {
'content-type': 'x-www-form-urlencoded',
'frank': '18'
}
}).then(
(responseText)=>{console.log("success")},
(request)=>{console.log("fail")}
)
})
这样如果成功或者失败后有多个函数需要执行,可以继续.then()。