基于Promise封装AJAX

本文展示了一个初级前端开发者如何封装一个Ajax函数,包括参数处理、兼容性处理、错误处理和超时设置。通过这个实例,可以了解前端与服务器交互的基本流程和常见优化技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有什么优化的可以一起讨论,本人初级前端一枚

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<script>
    function configAjax({baseUrl, timeout}) {
        // 处理参数的
        function objToStr(data) {
            data = data || {}
            let keys = Object.keys(data)
            let str = ""
            for (let i = 0; i < keys.length; i++) {
                const key = keys[i]
                const val = data[keys[i]]
                str += `&${key}=${val}`
            }
            str = str.substring(1)
            return encodeURIComponent(str)
        }

        return function ({path = "", data = {}, method = "get"}) {
            return new Promise((resolve, reject) => {
                let xhr = null
                let timerId = null
                let params = objToStr(data)

                // 兼容性
                if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
                    xhr = new XMLHttpRequest()
                } else {// code for IE6, IE5
                    xhr = new ActiveXObject("Microsoft.XMLHTTP")
                }

                // 发起请求
                if (method.toLowerCase() === "get") {
                    path += params ? "?" : ""
                    xhr.open(method, baseUrl + path + params, true);
                    xhr.send()
                } else {
                    xhr.open(method, baseUrl + path, true)
                    xhr.send(params)
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
                }

                xhr.onreadystatechange = () => {
                    if (xhr.readyState === 4) {
                        clearInterval(timerId)
                        if (xhr.status >= 200 && xhr.status < 300 ||
                            xhr.status === 304) {
                            resolve(JSON.parse(xhr.responseText))
                        } else {
                            reject("请求异常:" + xhr.status)
                        }
                    }
                }
                if (timeout) {
                    timerId = setInterval(() => {
                        xhr.abort()
                        reject("已超时,中断请求")
                    }, timeout || 6000)
                }
            })
        }
    }

    let myAjax = configAjax({
        baseUrl: "http://127.0.0.1:3666",
        timeout: 10000
    })
    myAjax({
        path: "/api/get",
        data: {
            name: "晨晨",
            age: 66
        }
    }).then(res => {
        console.log(res)
    })
</script>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值