原生JS封装AJAX

时间:2021-7-3 作者:qvyue

1. AJAX的封装

/* === AJAX的封装 === */
function ajax(ops){
    // 处理参数及默认值
    let {url, data={}, type="get", success, error} = ops;
    // 处理数据及url地址
    let str = "";
    for(let i in data){
        str += `${i}=${data[i]}&`;
    }
    url = type==="get" ? `${url}?${str}_g-xy_=${Date.now()}` : url;
    // 处理xhr的兼容
    let xhr = null;
    if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest();
    }else{
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    // 开启AJAX并监听状态
    xhr.open(type,url,true);
    xhr.addEventListener("load", ()=>{
        if(xhr.status === 200){
            success(xhr.responseText);
        }else{
            error && error(xhr.status);
        }
    });
    // 判断发送方式
    if(type === "get"){
        xhr.send();
    }else if(type === "post"){
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xhr.send(str.slice(0,str.length-1));
    }
}
/* ===== END ===== */

2. JSONP的封装

/* === JSONP的封装 === */
function jsonp(ops){
    // 处理参数及默认值
    let {url, data={}, fieldName, success} = ops;
    // 处理数据
    let str = "";
    for(let i in data){
        str += `${i}=${data[i]}&`;
    }
    // 向页面添加script标签并请求url
    let script = document.createElement("script");
    document.body.appendChild(script);
    script.src = `${url}?${str}_g-xy_=${Date.now()}`;
    // 设置全局函数接收数据
    window[data[fieldName]] = res=>{success(res)}
}
/* ===== END ===== */

3. AJAX和JSONP的合并封装

/* === AJAX和JSONP的封装 === */
function request(ops){
    let {url, success, data={}, type="get", error, async=true, timeout=2000, jsonp="callback"} = ops;
    let str = "";
    for(let i in data){
        str += `${i}=${data[i]}&`;
    }
    if(type !== "post"){
        url = url + "?" + str + "_g-xy_=" + Date.now();
    }
    if(type !== "jsonp"){
        let xhr = null;
        if(window.XMLHttpRequest){
            xhr = new XMLHttpRequest();
        }else{
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xhr.open(type, url, async);
        xhr.onload = ()=>{
            if(xhr.status === 200){
                success(xhr.responseText);
                error = null;
                success= null;
            }else{
                error && error(xhr.status);
                success = null;
                error = null;
            }
        }
        if(type === "get"){
            xhr.send();
        }else{
            xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xhr.send(str.slice(0,str.length-1));
        }
    }else{
        let script = document.createElement("script");
        document.body.appendChild(script);
        script.src = url;
        window[data[jsonp]] = res=>{
            success && success(res);
            error = null;
            success = null;
        }
    }
    setTimeout(() => {
        error && error("timeout");
        success = null;
        error = null;
    }, timeout);
}
/* ===== END ===== */

4. AJAX和JSONP的Promise封装

/* -------------------------
    AJAX和JSONP的Promise封装
   ------------------------- */
function request(ops){
    return new Promise((resolve,reject)=>{
        let {url, data={}, type="get", async=true, timeout=2000, jsonp="callback"} = ops;
        let str = "";
        for(let i in data){
            str += `${i}=${data[i]}&`;
        }
        if(type !== "post"){
            url = url + "?" + str + "_g-xy_=" + Date.now();
        }
        if(type !== "jsonp"){
            const xhr = new XMLHttpRequest();
            xhr.open(type, url, async);
            xhr.onload = ()=>{
                if(xhr.status === 200){
                    resolve(xhr.responseText);
                }else{
                    reject(xhr.status);
                }
            }
            if(type === "get"){
                xhr.send();
            }else{
                xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                xhr.send(str.slice(0,str.length-1));
            }
        }else{
            let script = document.createElement("script");
            document.body.appendChild(script);
            script.src = url;
            window[data[jsonp]] = res=>{
                resolve(res);
            }
        }
        setTimeout(() => {
            reject("timeout");
        }, timeout);
    })
}
/* ===== END ===== */
  • 以上代码有待完善,如有错误请指出,欢迎交流。
声明:本文内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:qvyue@qq.com 进行举报,并提供相关证据,工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。