ajax封装

function ajax(type, url, success, error) {
    var ajax = new XMLHttpRequest();
    if (type.toLowerCase() == 'post') {
        if (url.indexOf('?') == -1) {
            ajax.open(type, url, true);
            ajax.setRequestHeader('Content-type', 'application/x-www-formurlencoded');
            ajax.send();
        } else {
            url = url.split('?');
            ajax.open(type, url[0], true);
            ajax.setRequestHeader('Content-type', 'application/x-www-formurlencoded');
            ajax.send(url[1]);
        }
    } else {
        ajax.open(type, url, true);
        ajax.send();
    }
    ajax.onreadystatechange = function () {
        if (ajax.readyState == 4) {
            if (ajax.status == 200) {
                // 请求成功以后
                success && success(ajax.responseText);
            } else {
                // 错误信息
                error && error(ajax.status);
            }
        }
    }

}
原文地址:https://www.cnblogs.com/huchangwu/p/12048892.html