2021-07-11 ajax的三个函数封装:get,post,jsonp


function request(ops) {
    // 1.处理参数:可选参数要有默认值,可选函数须先判断
    let { url, success, type = "get", data = {}, error, timeout = 1000, dataType = "text", filedName = "" } = ops;
    //4.处理数据
    let str = '';
    for (var i in data) {
        str += `${i}=${data[i]}&`;
    }
    //5.根据请求方式拼接url
    if (type !== "post") {
        url = url + "?" + str + "_qft_=" + Date.now();
    }
    //2.判断开启ajax
    let xhr;
    if (type !== "jsonp") {
        //3.创建xhr对象
        xhr = new XMLHttpRequest();
        //设置请求
        xhr.open(type, url);
        //6.开启监听
        xhr.onload = function() {
                if (xhr.status == 200) { //成功
                    const res = dataType === "json" ? JSON.parse(xhr.responseText) : xhr.responseText;
                    //ajax的成功:成功后不能失败,也不能再次成功
                    success && success(res);
                    error = null;
                    success = null;
                } else { //失败
                    //ajax的失败
                    error && error(xhr.status);
                    success = null;
                    error = null;
                }
            }
            //8.根据get或者post执行send
        if (type == "get") {
            xhr.send();
        } else {
            xhr.setRequestHeader("Content-Type", "application/x-www-urlencoded")
            xhr.send(str.slice(0, str.length - 1));
        }
    } else {
        //9.jsonp请求:动态创建script
        let script = document.createElement("script");
        script.id = "abc";
        script.src = url;
        document.body.appendChild(script);
        //10.声明全局变量:在局部声明全局
        window[data[filedName]] = function(res) {
            res = dataType === "json" ? JSON.parse(res) : res;
            //11.jsonp的成功
            success && success(res);
            //15.1jsonp请求成功后删除 script标签
            script && script.remove();
            error = null;
            success = null;
        }
    }
    setTimeout(() => {
        // 12.超时
        // jsonp没有状态可以判断,只能按照超时报错
        error && error("timeout");
        const s = document.getElementById("abc");
        s && s.remove();
        success = null;
        error = null;
    }, timeout)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端OnTheRun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值