js原生Ajax fetch与XMLHttpRequest整合

2018-08-22  本文已影响0人  管子先生

相关API

Fetch API:

https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API

XMLHttpRequest API:

https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest

源码:

/**
 * Ajax
 * @param {string}      opt.method  http连接的方式,包括POST和GET两种方式
 * @param {string}      opt.url     发送请求的url
 * @param {boolean}     opt.async   是否为异步请求,true为异步的,false为同步的,不支持fetch
 * @param {object}      opt.data    发送的参数,格式为对象类型
 * @param {function}    opt.success ajax发送并接收成功调用的回调函数
 * @param {function}    opt.error   ajax发送并接收错误请求的回调函数
 */
function ajax(opt) {    
    // 初始化配置
    opt = opt || {};
    opt.method = opt.method.toUpperCase() || 'GET';
    opt.url = opt.url || '';
    opt.async = opt.async === false ? false : true;
    opt.data = opt.data || null;
    opt.success = opt.success || function () { };
    opt.error = opt.error || function () { };
    // 参数序列化
    var params = [];
    for (var key in opt.data) {
        params.push(key + '=' + opt.data[key]);
    }
    var postData = params.join('&');
    // 判断浏览器是否支持fetch及是否为同步请求
    if (fetch && opt.async) {
        // fetch配置
        var fetchConfig = {
            method: opt.method,
            credentials: 'include',         // 请求带入cookie
            headers: new Headers({
                'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
            })
        };
        if (opt.method === "POST") {
            fetchConfig.body = postData;
        } else if (opt.method === "GET") {
            opt.url += "?" + postData;
        } else {
            throw new TypeError("method类型错误!");
        }
        fetch(opt.url, fetchConfig)
            .then(function (response) {
                if (response.status === 200) {
                    try {
                        return response.json();
                    } catch (error) {
                        opt.error(error);
                    }
                } else {
                    opt.error(response.status + ' ' + response.statusText);
                }
            })
            .then(function (myJson) {
                opt.success(myJson);
            })
            .catch(function (err) {
                opt.error(err);
            });
    } else {
        // 不支持则使用xhr
        var xmlHttp = null;
        if (XMLHttpRequest) {
            xmlHttp = new XMLHttpRequest();
        } else {
            xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
        }
        if (xmlHttp == null) {
            alert("您的浏览器不支持AJAX!");
            return;
        }
        xmlHttp.onreadystatechange = function () {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                opt.success(JSON.parse(xmlHttp.responseText));
            } else if (xmlHttp.readyState == 4 && xmlHttp.status !== 200) {
                opt.error(xmlHttp.status + ' ' + xmlHttp.responseText);
            }
        }
        if (opt.method.toUpperCase() === 'POST') {
            xmlHttp.open(opt.method, opt.url, opt.async);
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
            xmlHttp.send(postData);
        } else if (opt.method.toUpperCase() === 'GET') {
            xmlHttp.open(opt.method, opt.url + '?' + postData, opt.async);
            xmlHttp.send(null);
        }
        xmlHttp.onerror = function (err) {
            opt.error(err);
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读