使用promise封装ajax异步网络操作

144 阅读1分钟
  /**
 * 使用promise封装ajax异步网络操作
 */
function myAjaxPromise(options) {
   return new Promise(function (resolve, reject) {
        //封装异步ajax操作

        //1. 获取XMLHttpRequest
        const xhr = new window.XMLHttpRequest()
        //格式化参数
        let parms = formatParma(options.data)
        if (options.method.toUpperCase() == 'GET') {
            //2. 建立连接
            xhr.open(options.method, options.url + '?' + parms) //http://ip:port/login?username='admin'&age=21
            xhr.send()
        } else if (options.method.toUpperCase() == 'POST') {
            xhr.open(options.method, options.url)
            //3.发送请求
            //设置传输的参数数据类型content-type, 支持名称1=值1&名称2=值2
            xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
            xhr.send(parms)
        }

        //4.处理响应数据
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    let result = xhr.responseText
                    result = JSON.parse(result) //json字符串转json对象
                    resolve(result)

                } else {
                    reject(xhr.status + xhr.statusText)
                }
            }
        }

    })
}

//处理post提交的数据
function formatParma(obj) {
    let arr = []
    for (let key in obj) {
        let item = `${key}=${obj[key]}` //username='admin'
        arr.push(item) //[username='admin', age=21,headerimg="http://222.jpg"]
    }
    let str = arr.join('&') //`username='admin' & age=21& headerimg="http://222.jpg"
    return str
}