当前位置:首页 > 前端 > 正文

简单封装一个ajax插件

function ajax(options) {
    options = options || {};
    options.type = options.type || ‘get‘;
    options.type = options.data || {};
    options.dataType = options.dataType || ‘text‘;


    //IE6以下无法使用
    let xhr = new XMLHttpRequest();
    // 数据修改
    let arr = [];
    for (let name in options.data) {
        arr.push(`${name}=${options.data[name]}`)
    }
    let strData = arr.join(‘&‘);
    if (options.type == ‘post‘) {
        xhr.open(‘post‘, options.url, true);
        xhr.setRequestHeader(‘content-type‘, ‘application/x-www-form-urlencoded‘)
        xhr.send(strData);
    } else {
        xhr.open(‘get‘, options.url + ‘?‘ + strData, true);
        xhr.send();
    }
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
                let data = xhr.responseText;
                switch (options.dataType) {
                    case ‘json‘:
                        if (window.JSON && JSON.parse) {
                            data = JSON.parse(data);
                        } else {
                            data = eval(‘(‘ + str + ‘)‘)
                        }
                        break;
                    case ‘xml‘:
                        data = xhr.responseXML;
                        break
                }
                options.success && options.success(data);
            } else {
                options.error && options.error()
            }
        }
    }
}