list ajax封装,将原生的ajax封装成promise

这篇博客介绍了如何使用Promise将原生Ajax请求进行封装,包括GET和POST方法的实现,并展示了如何处理成功和失败的回调。通过创建一个myAjax函数,它能处理异步操作并支持done和fail方法来注册回调。在测试示例中,展示了一个GET请求到time.php的使用。
摘要由CSDN通过智能技术生成

//原生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)

})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值