封装ajax

const $ = (function (window) {

    function formatData(data) {
        let str = '';
        for(let prop in data) {
            // str += `${prop}=${data[prop]}&`;
            str += prop + "=" + data[prop] + "&";
        }
        return str.slice(0, str.length - 1);
        // return str.replace(/&$/, "");
    }

    function _getData(opt) {
        var opt = opt || {},
            xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"),
            type = (opt.type || "GET").toLowerCase(),
            url = opt.url,
            data = opt.data || {},
            async = opt.async || true;
            success = opt.success || function() {},
            error = opt.error || function() {},
            complete = opt.complete || function() {};

        if(!url) {
            throw Error('请输入URL');
        }
        xhr.open(type, url, async);
        type === "POST" ? xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded") : null;
        xhr.send(type === "GET" ? null : formatData(data));
        xhr.onreadystatechange = function () {
            if(xhr.readyState === 4 && xhr.status === 200) {
                success(JSON.parse(xhr.responseText));
            } else if(xhr.status === 404) {
                error();
            }
            complete();
        }
    }

    return {
        ajax(opt) {
            _getData(opt);
        },
        get(url, cb) {
            _getData({
                url,
                type: "GET",
                success: cb
            });
        },
        post(url, data, cb) {
            _getData({
                url,
                data,
                type: "POST",
                success: cb
            });
        }
    };

})(window);

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。