原生js封装ajax方法(支持jsonp)

直接上代码
/**
 * 对封装好的ajax请求进行调用
 * */
ajax({
    url: "", //请求地址
    type: 'GET', //请求方式
    data: {
        name: 'monoplasty',
        age: '23',
        email: 'monoplasty@aliyun.com'
    }, //请求参数
    success: function(response, xml) {
        console.log(response); //   此处执行请求成功后的回调
    },
    fail: function(status) {
        console.log('状态码为' + status); // 此处为请求失败后的回调
    }
});

/**
* options {type, data: Object, success: Function, fail: Function }
*/
function ajax(options) {
    options = options || {};
    options.type = (options.type || "GET").toUpperCase();
    options.dataType = options.dataType || 'json';
    options.async = options.async || true;
    var params = getParams(options.data);
    var xhr;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else {
        xhr = new ActiveXObject('Microsoft.XMLHTTP')
    }
    xhr.onreadystatechange = function() {
        if(opt.dataType === 'json'){
            if (xhr.readyState == 4) {
                var status = xhr.status;
                if (status >= 200 && status < 300) {
                    // 如果需要像 html 表单那样 POST 数据,请使用 setRequestHeader() 来添加 http 头。
                    options.success && options.success(xhr.responseText, xhr.responseXML);
                } else {
                    options.fail && options.fail(status);
                }
            }
        } else {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                var oScript = document.createElement('script');
                document.body.appendChild(oScript);

                var callbackname = 'monoplasty'
                oScript.src = opt.url + "?" +  params+'&callback='+callbackname;

                window['monoplasty'] = function(data) {
                    opt.success(data);
                    document.body.removeChild(oScript);
                };
            }
        }

    };
    if (options.type == 'GET') {
        xhr.open("GET", options.url + '?' + params, options.async);
        xhr.send(null)
    } else if (options.type == 'POST') {
        xhr.open('POST', options.url, options.async);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.send(params);
    }
}
function getParams(data) {
    var arr = [];
    for (var param in data) {
        arr.push(encodeURIComponent(param) + '=' + encodeURIComponent(data[param]));
    }
    return arr.join('&');
}

原生js仿jquery实现对Ajax的封装,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值