原生JavaScript-ajax请求封装

采用原生JavaScript、promise封装get、post、jsonp请求

var http = (function () {

    /**
     * param 将要转为URL参数字符串的对象
     * key URL参数字符串的前缀
     * encode true/false 是否进行URL编码,默认为true
     * return URL参数字符串
     */
    var urlEncode = function (param, key, encode) {
        if (param == null) return '';
        var paramStr = '';
        var t = typeof (param);
        if (t == 'string' || t == 'number' || t == 'boolean') {
            paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param);
        } else {
            for (var i in param) {
                if(param.hasOwnProperty(i)){
                    var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
                    paramStr += urlEncode(param[i], k, encode);
                }
            }
        }
        return paramStr;
    };

    var $http = function (options) {

    };

    $http.config = {
        timeout: 0,//设置超时
        ontimeout: function () {return '连接超时'}//设置超时回调
    };

    /**
     * GET请求
     * @param url 请求地址
     * @param options 请求选项 {data:'一个普通对象,通过请求发送给服务器',
     * dataType:'从服务器返回的预期的数据类型,,默认json'}
     * return promise
     */
    $http.get = function (url, options) {
        return new Promise(function (resolve, reject) {
            if(url.indexOf('?') != -1){
                url += urlEncode(options.data);
            }else{
                url += '?' + urlEncode(options.data).slice(1);
            }
            var xhr = new XMLHttpRequest();
            xhr.timeout = $http.config.timeout;
            xhr.open("GET", url, true);
            xhr.responseType = options.dataType || "json";
            xhr.onload = function () {
                resolve(this.response);
            };
            xhr.error = function () {
                reject(this.statusText);
            };
            xhr.ontimeout = function () {
                reject($http.config.ontimeout());
            };
            xhr.send();
        });
    };

    /**
     * POST请求
     * @param url 请求地址
     * @param options 请求选项 {data:'一个普通对象,通过请求发送给服务器',
     * dataType:'从服务器返回的预期的数据类型,,默认json'}
     * return promise
     */
    $http.post = function (url, options) {
        return new Promise(function (resolve, reject) {
            var xhr = new XMLHttpRequest();
            xhr.timeout = $http.config.timeout;
            xhr.open("POST", url, true);
            xhr.responseType = options.dataType || "json";
            xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded; charset=UTF-8");
            xhr.onload = function () {
                resolve(this.response);
            };
            xhr.error = function () {
                reject(this.statusText);
            };
            xhr.ontimeout = function () {
                reject($http.config.ontimeout());
            };
            xhr.send(urlEncode(options.data).slice(1));
        });
    };
    $http.jsonpCallback = function () {};
    $http.jsonp = function (url,options) {
        return new Promise(function (resolve, reject) {
            var head = document.getElementsByTagName('head')[0];
            var script = document.createElement('script');
            var timer;
            head.appendChild(script);
            $http.jsonpCallback = function (data) {
                resolve (data);
                $http.jsonpCallback = function () {};
                clearTimeout(timer);
            };
            options.data.callback = 'http.jsonpCallback';
            if(url.indexOf('?') != -1){
                url += urlEncode(options.data);
            }else{
                url += '?' + urlEncode(options.data).slice(1);
            }
            script.src = url;
            if($http.config.timeout){
                timer = setTimeout(function () {
                    reject($http.config.ontimeout());
                },$http.config.timeout);
            }
        });
    };
    return $http;
})();

 

posted @ 2016-12-10 17:35  minimal虾米  阅读(160)  评论(0编辑  收藏  举报