封装自己的Ajax (仿jQuery)

本人纯小白,自己仿jQuery封装了Ajax请求,欢迎大佬来指点!

(function () {
    /*
    我们规定传递的是一个对象参数如下:
    url: 请求地址
    type:请求类型
    data:参数
    success: 回调函数
    */
    var $ = {
        //get请求封装
        get: function (option) {
            option.data = this.convertData(option.data)
            //创建Ajax对象
            var xhr = new XMLHttpRequest();
            xhr.open(option.type, option.url + '?' + option.data);
            xhr.send();
            //监听请求状态改变事件
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var result = JSON.parse(xhr.responseText)
                    option.success(result)
                }
            }
        },

        //post请求封装
        post: function (option) {
            option.data = this.convertData(option.data);
            //创建Ajax对象
            var xhr = new XMLHttpRequest();
            xhr.open(option.type, option.url);
            xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
            xhr.send(option.data);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var result = JSON.parse(xhr.responseText)
                    option.success(result)
                }
            }

        },
        //Ajax请求封装
        ajax: function (option) {
            if (option.type.toUpperCase() === 'GET') {
                this.get(option)
            } else {
                this.post(option)
            }

        },

        //数据转换
        convertData: function (data) {
            var arr = [];
            for (var key in data) {
                arr.push(key + '=' + data[key])
            }
            return arr.join('&')
        }
    }


    window.$ = $
})()

觉得不错的点个赞吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值