首页 > Web开发 > 详细

简单封装一个ajax插件

时间:2019-01-29 22:31:34      阅读:200      评论:0      收藏:0      [点我收藏+]
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()
            }
        }
    }
}

 

简单封装一个ajax插件

原文:https://www.cnblogs.com/yang656/p/10336003.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!