//原生ajax封装成promise
function myAjax(method,url,params){
this.state = 'FULFILLED'
this.fulfillList = []
this.rejectList = []
;(function(that){
var data = null
method = method.toUpperCase()
if(typeof params == 'object'){
var _arr = []
for(var item in params){
_arr.push(item+"="+params[item])
}
params = _arr.join('&')
}
if(method === 'GET'){
url +='?'+params
}
if(method === 'POST'){
data = params
}
//start
var xhr = new XMLHttpRequest()
xhr.open(method,url)
xhr.setRequestHeader('Content-type','appliction/x-www-form-urlencoded')
xhr.addEventListener('readystatechange',function(){
if(this.readyState !== 4)return;
if(this.status !== 200)
reject({status:this.status,statusText:this.statusText})
else
resolve(this.responseText)
})
xhr.send(data)
//成功
var resolve = function(data){
that.state = 'FULFILLED'
setTimeout(function () {
that.fulfillList.forEach(function (itemFn,key,arr) {
itemFn(data)
arr.shift()
})
},0)
}
//失败,执行失败队列的函数
var reject = function(data){
that.state = 'REJECTED'
setTimeout(function () {
that.rejectList.forEach(function (itemFn,key,arr) {
itemFn(data)
arr.shift()
})
},0)
}
})(this)
}
//成功回调函数
myAjax.prototype.done = function(handle){
if(typeof handle === 'function')
this.fulfillList.push(handle)
else
throw new Error('回调函数出错')
return this
}
//失败回调函数
myAjax.prototype.fail = function(handle){
if(typeof handle === 'function')
this.rejectList.push(handle)
else
throw new Error('回调函数出错')
return this
}
//失败成功写在一个方法内
myAjax.prototype.then = function(fulfill,reject){
this.done(fulfill||function () {})
.fail(reject||function(){})
return this
}
//测试ajax
var ajax = new myAjax('get','./time.php',{a:'123'})
ajax.then(function(data){
console.log(data)
},function(data){
console.log(data)
})