封装AJAX(带详细注释)

今天我们进行AJAX的封装,将AJAX进行封装方便我们的使用

javascript 复制代码
    <script>
        //将对象封装为字符串
        function swithStr(obj) {
            let str = ''
            for (k in obj) {
                str += `${k}=${obj[k]}&`
            }
            return str.slice(0, -1)
        }
        function ajax(option = {}) {
            //验证是否传了url url必须传
            if (option.url == undefined) throw new Error('必须传url,不能为空')

            //判断是否传了参数 参数只能穿post get
            if (!(option.method == undefined || /^(POST|GET)$/i.test(option.method)))             throw new Error('参数只能传POST或者GET')

            //判断是否传了异步 传异步参数只能是布尔值或者不填
            if (!(option.async == undefined || typeof option.async == 'boolean')) throw new Error('async参数只能穿布尔类型或者undefined')

            //判断是否传了参数 参数只能穿Object类型的或者不传 //option.data.constructor == Object
            if (!(option.data == undefined || typeof option.data == 'string' || typeof option.data == 'object')) throw new Error('携带的参数只能填对象或者不填')

            //判断是否传了请求头,请求头只能传对象或者不会窜
            if (!(option.header == undefined || typeof option.data == 'object')) throw new Error('请求头只能传对象或者undefined')

            //判断是否需要解析响应体 只能传string或者json
            if (!(option.dataType == undefined || /^(JSON|STRING)$/i.test(option.dataType))) throw new Error('响应体只能传string或者json')


            //准备一套默认值
            const _default = {
                url: option.url,
                method: option.method || 'GET',
                async: option.async ?? true,
                data: option.data || '',
                header: { 'content-type': 'application/x-www-form-urlencoded', ...option.header },
                dataType: option.dataType ?? 'string'
            }
            //如果是GET方式,处理data

            if (typeof option.data == 'object') _default.data = swithStr(option.data)
            if (/^GET$/i.test(_default.method) && _default.data) _default.url += '?' + _default.data

            //创建Promise对象用来处理异步
            const p = new Promise((resolve, reject) => {
                const xhr = new XMLHttpRequest()
                xhr.open(_default.method, _default.url, _default.async)
                xhr.onload = function () {
                    if (_default.dataType == 'string') {
                        resolve({
                            code: 1,
                            message: '成功',
                            info: xhr.responseText
                        })
                    }
                    try {
                        const res = JSON.parse(xhr.responseText)
                        resolve({
                            code: 1,
                            message: '成功',
                            info: res
                        })
                    } catch (err) {
                        resolve({
                            code: 0,
                            message: '失败',
                            info: err
                        })
                    }
                }

                //POST使用请求头
                if (/^POST$/i.test(_default.method)) xhr.setRequestHeader('content-type', _default.header['content-type']);
                //设置token请求头
                if (_default.header.authorization) xhr.setRequestHeader('authorization', _default.header['authorization']);

                //发送请求
                /^post$/i.test(_default.method) ? xhr.send(_default.data) : xhr.send()


            })
            return p
        }



 async function fff() {
            const a = await ajax({ method: 'get', url: 'http://localhost:8888/test/first', async: false })
            console.log(a)
            const b = await ajax({ method: 'get', url: 'http://localhost:8888/test/second', async: false })
            console.log(b)
            const c = await ajax({ method: 'get', url: 'http://localhost:8888/test/third', async: false, data: { name: 'zhangsan', age: 18 } })
            console.log(c)
            const d = await ajax({ method: 'post', url: 'http://localhost:8888/test/fourth', async: false, data: { name: 'zhangsan', age: 18 } })
            console.log(d)

            const e = await ajax({ method: 'post', url: 'http://localhost:8888/users/login', async: true, data: { username: 'admin', password: '123456' } })
            console.log(e)
        }

        fff()

    </script>
相关推荐
六月的可乐6 分钟前
【干货】小程序虚拟瀑布流探索小结
前端·react.js·小程序
techdashen12 分钟前
Rust 项目管理动态 — 2026 年 3 月
前端·人工智能·rust
原则猫11 小时前
HOOKS 背后机制
前端
码语智行11 小时前
首页导航跳转功能深度解析-系统内和系统外
前端
阿猫的故乡12 小时前
Vue过渡动画从入门到装X:淡入淡出、滑动、列表动画、第三方库全搞定
前端·javascript·vue.js
IManiy12 小时前
总结之Vibe Coding前端骨架
前端
JS菌12 小时前
AI Agent 沙箱双层防护体系:从权限过滤到内核隔离的完整实现
前端·人工智能·后端
Aphasia31112 小时前
从输入URL到页面展示全流程
前端·面试
我叫黑大帅13 小时前
前端如何竖屏固定视口背景
前端·javascript·面试
abcy07121313 小时前
python pandas csv异步后台清洗前端优先返回成功信息
前端·python·pandas