首页 > 试题广场 >

将原生的ajax封装成promise

[问答题]
   //原生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)
    }) 

编辑于 2019-03-21 15:31:41 回复(0)
    function newAjax (method,url,params,headers){
        return new Promise((resolve,reject)=>{
            let req = new XMLHttpRequest();   //生成xhr对象
            if(typeof params == 'object'){    //获取传入参数,get是加在url后面,post加在send中
                var arr = []
                for(var key in params){
                    arr.push(key +"="+ params[key])
                }    
                params = arr.join('&')
            }
            if(method === 'GET'){
                url = url +"?"+ params
            }
            var body = null
            if(method === 'POST'){
                body = params
            }
            req.open(method,url)

            if(headers != null){   //设置头部
                for(const key in headers)
                {    
                    let value = headers[key]
                    req.setRequestHeader(key,value)
                }
            }
            req.send(body)

              req.onreadystatechange = ()=>{
                  if(req.readyState === 4&&req.status ===200){
                      resolve.call(undefined,req.resposeText)
                  
                  else{
                      reject.call(undefined,req)
                  }
              }
        })
    }
发表于 2019-03-28 17:10:14 回复(0)