封装一个简单的ajax请求

发布时间:2022-07-01 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了封装一个简单的ajax请求脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

记录自己第一次封装ajax,肯定有很多考虑不周到,如有错误请指出,本人必将虚心改正。

/**
 * 
 * @param {Object} obj =>header:请求头;url:请求地址;methods:请求方法;data:请求参数
 * @returns {JSON} 
 * @returns {XML}
 */

const ajax = function (obj) {
    //返回promise对象
    return new Promise((res, rej) => {
        let xhr = null
        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest()
        } else {
            //兼容ie5、ie6
            xhr = new ActiveXObject('Microsoft.XMLHTTP')
        }
        xhr.onreadystatechange = function () {
            try {
                /**
                 * readyState值的含义
                 * 0: 请求未初始化
                 * 1: 服务器连接已建立
                 * 2: 请求已接收 接收到了响应头
                 * 3: 请求处理中 正在下载响应体
                 * 4: 请求已完成,且响应已就绪
                 */
                if (xhr.readyState == 4 && xhr.status == 200) {
                    if (xhr.responseXML) {
                        res(xhr.responseXML)
                    } else {
                        res(JSON.parse(xhr.responseText))
                    }
                } else {
                    if (xhr.status == 404) throw '404,未找到页面'
                }
            } catch (e) {
                rej(e)
            }
        }

        //参数处理,当请求方式为get时,需要将参数加在请求地址后面。post则直接传参
        let data = '?'
        if (obj.data != undefined) {
            for (const key in obj.data) {
                data += key + '=' + obj.data[key] + '&'
            }
            data.substring(data.length - 1)
            obj.data = data
        }
        if (obj.methods == 'GET' || obj.methods == 'get') {
            obj.url += data
        }


        xhr.open(obj.methods, obj.url, true) //发起请求

        //对请求头进行处理
        if (obj.header != undefined) {
            let key = Object.keys(obj.header)
            xhr.setRequestHeader(key[0], obj.header[key[0]])
        }

        //发送请求
        xhr.send(obj.data)
    })
}

脚本宝典总结

以上是脚本宝典为你收集整理的封装一个简单的ajax请求全部内容,希望文章能够帮你解决封装一个简单的ajax请求所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: