工作中jsonp 与ajax的封装

 ajaxJsonp: function(opts) {

            var opts = opts || {},

                //url参数,必填
                url = opts.url,

                //jsonp函数名,必填
                jsonpCallback = opts.jsonpCallback || "callback",

                //成功回调,可选
                success = opts.success,

                //错误回调,可选
                error = opts.error,

                //地址参数,可选
                data = opts.data || {},

                //请求超时,可选

                time = opts.time;


            if (!url || !jsonpCallback) {

                throw "参数非法!";
            }

            var nonce = String(Math.random()).replace(/\D/, ''),
                callbackName = 'jsonp_' + nonce,
                head = document.getElementsByTagName('head')[0],
                script = document.createElement("script");

            data[jsonpCallback] = callbackName;

            global[callbackName] = function() {

                head.removeChild(script);

                global[callbackName] = undefined;

                clearTimeout(script.timer);

                success && success(arguments[0]);

            }

            var params = this.formatParams(data);

            script.src = url + '?' + params;

            head.appendChild(script);

            //超时
            if (time) {

                script.timer = setTimeout(function() {

                    head.removeChild(script);

                    global[callbackName] = undefined;

                    error && error({
                        message: "超时!"
                    });

                }, time);
            }
        },
        /* 格式化url参数
         * @name {function} formatParams
         * @param {object} data 参数对象
         * @return {string}
         */
        formatParams: function(data) {

            var paramsArr = [];

            for (var name in data) {

                paramsArr[paramsArr.length] = encodeURIComponent(name) + '=' + encodeURIComponent(data[name]);
            }

            return paramsArr.join('&');
        },
        /* 创建xmlhttp对象
         * @name {function} createAjax
         * @return {object}  xhr xmlhttp实例
         */
        createAjax: function() {

            var xhr = null;

            try { //非IE浏览器

                xhr = new XMLHttpRequest();

            } catch (e1) {

                try { //IE浏览器

                    xhr = new ActiveXObject("Microsoft.XMLHTTP");


                } catch (e2) {

                    alert("您的浏览器不支持Ajax!");

                }

            }

            return xhr;

        },
        /* ajax
         * @name {function} ajax
         * @param {object} opts 参数对象
         *   @property {string} url 请求地址,必填
         *   @property {string} type  请求类型,可选,默认为get
         *   @property {string} dataType 请求返回的类型,可选,默认为text
         *   @property {object} data 在post请求时传递的参数,可选
         *   @property {function} success 成功回调,可选
         *   @property {function} error 错误回调,可选
         */
        ajax: function(opts) {

            var opts = opts || {},

                //type参数可选,默认为get
                type = opts.type || "get",

                //url参数,必填
                url = opts.url,

                //data参数可选,在post请求时需要
                data = opts.data,

                cache = opts.cache || false,

                //dataType参数可选,默认为text
                dataType = opts.dataType || "text",

                //成功回调函数可选
                success = opts.success,

                //错误回调函数可选
                error = opts.error

            if (!url || !success) {
                throw "参数非法!";
            }

            var xhr = this.createAjax();
            //如果配置缓存
            if (cache) {

                xhr.open(type, url, true);

            } else {

                var nonce = String(Math.random()).replace(/\D/, '');

                if (url.indexOf('?') != -1) {

                    xhr.open(type, url + '&random=' + nonce, true);

                } else {

                    xhr.open(type, url + '?random=' + nonce, true);
                }
            }

            if (type == "GET" || type == "get") {

                xhr.send(null);

            } else if (type == "POST" || type == "post") {

                xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");

                xhr.send(data);

            }

            xhr.onreadystatechange = function() {

                //请求成功
                if (xhr.readyState == 4 && xhr.status == 200) {

                    //普通文本
                    if (dataType == "text" || dataType == "TEXT") {

                        success && success(xhr.responseText);

                        //接收xml文档
                    } else if (dataType == "xml" || dataType == "XML") {

                        success && success(xhr.responseXML);

                        //将json字符串转换为对象
                    } else if (dataType == "json" || dataType == "JSON") {

                        success && success(eval("(" + xhr.responseText + ")"));

                    }

                    //请求失败
                } else {

                    error && error({
                        message: "请求失败!"
                    });

                }

            }
        },

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值