JQ版AJAX源码简单处理

+ function () {
    //---------------默认值
    var defaults = {
        url: '',
        method: 'get',
        async: true,
        data: null,
        dataType: 'json',
        cache: true,
        timeout: null,
        headers: null,
        success: null,
        error: null
    }

    function ajax(options) {
        return new init(options)
    }
    ajax.prototype = {
        constructor: ajax,
        send: function send() {
            //---------------对象解构
            var {
                url,
                method,
                async,
                data,
                dataType,
                timeout,
                cache,
                success,
                error,
                headers
            } = this.options;
            var xhr = this.xhr= new XMLHttpRequest;
            //------------------------处理data
            data = this.handleData();
            var reg = /^(get|delete|head|options)$/i;
            if (data && reg.test(method)) {
                url += `${this.hasQuestion(url)}${data}`;
                data = null;
            }
            //---------------------处理缓存-->cache
            if (reg.test(method) && !cache) {
                var time = new Date().getTime();
                url += `${this.hasQuestion(url)}-=${time}`;
            }
            //----------------------处理timeout
            if (timeout) xhr.timeout = timeout;
            xhr.open(method, url, async);       
            //----------------处理请求头headers
            if (headers && toString.call(headers) == "[object Object]") {
                for (var key in headers) {
                    if (!headers.hasOwnProperty(key)) break;
                    xhr.setRequestHeader(key, encodeURI(headers[key]))
                }
            }
            xhr.onreadystatechange = () => {
                var str = "";
                if (xhr.readyState === 4) {
                    if (/^(2|3)\d{2}$/.test(xhr.status)) {
                        switch (dataType.toUpperCase()) {
                            case 'JSON':
                                str = JSON.parse(xhr.response)
                                break;
                            case 'TEXT':
                                str = xhr.responseText;
                                break;
                            case 'XML':
                                str = xhr.responseXML;
                                break;
                        }
                        success && success(str, xhr.statusText, xhr)
                    } else {
                        error && error(xhr.response, xhr.statusText, xhr)
                    }
                }
            }
            xhr.send(data)
        },
        hasQuestion: function hasQuestion(url) {
            return url.includes('?') ? "&" : "?";
        },
        //---------------对象转字符串
        handleData: function handleData() {
            var data = this.options.data;
            if (data == undefined || typeof data === "string") return data;
            var res = "";
            for (var key in data) {
                if (!data.hasOwnProperty(key)) break;
                res += `${key}=${data[key]}&`
            }
            return res.slice(0, res.length - 1)
        }
    }

    function init(options) {
        this.options = Object.assign({}, defaults, options);
        if (!options.url) throw new Error('url must be a area');
        this.send()
    }
    init.prototype = ajax.prototype;
    window.ajax = window._ = ajax
}()

_({
    url: 'data.json',
    method: 'get',
    async: true,
    cache: false,
    data: {
        sex: 'men',
        job: 'web'
    },
    headers: {
        name: 11,
        age: 22
    },
    success: (data, statusText, xhr) => {
        console.log(data, statusText, xhr);
    },
    error: (data, statusText, xhr) => {
        console.log(data, statusText, xhr);
    }
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值