原生JS封装ajax以及request

一、封装原生的xhr为ajax类

xhr以及用法见之前的文章

1、根据url确定请求的头部以及别的信息。

    var _headerConfig = {};
    if(url.indexOf('getcaptcha') !== -1) {
        _headerConfig = {
            Accept: 'image/png',
            responseType: 'arraybuffer',
        }
    } else if(url.indexOf('files/upload') !== -1) {
        _headerConfig = {
            'Content-Type': 'multipart/form-data',
            responseType: 'json',
        }
    } else {
        _headerConfig = {
            'Content-Type': 'application/json',
            Accept: 'application/json',
            responseType: 'json',
        }
    }

2、根据参数信息中的信息,确定请求的方法以及请求的参数

    if("method" in options) {
        options.method = options.method.toUpperCase();
    } else {
        options.method = "GET";
    }
    if(options.method !== "GET") {
        if(!(options.params instanceof FormData)) {
            options.params = JSON.stringify(options.params);
        }
    }

3、打开xhr并且根据头部头部以及其他信息设置,发送

    this.xhr.open(options.method, url, true);
    for(var _i in _headerConfig) {

        if(_i === 'responseType') {
            this.xhr.responseType = _headerConfig[_i];
        } else {
            this.xhr.setRequestHeader(_i, _headerConfig[_i]);
        }
    }
    if(token) {
        this.xhr.setRequestHeader("token", token);
    }
    this.xhr.send(options.params);

4、实现链式编程:在每个函数的结尾return this;

5、实现完成后执行回调

这个问题结合链式编程一度的卡了很久。

ajax.prototype.complete = function(completeFunction) {
    this.xhr.onreadystatechange = function(e) {
        if(this.readyState === 4) {
            completeFunction(this);
        }
    }
    return this;
}

二、封装实用性的request类

在项目中经常需要将request进行封装,使用ajax类发起请求。拼接请求的地址函数。

1、创建拼接方法。

var requstUrl = {
    baseURL: URL,
    API: {
        NEWS: '/news',
        LOGIN: '/',
    },
    // api为API中的参数,用于拼接url
    // method为API后的地址,用于拼接url最后面的东西。
    // params为get请求需要的参数
    createUrl: function(api, method, params) {
        var _requestUrl = this.baseURL + this.API[api] + method;
        if(params) {
            for(var i of params) {
                _requestUrl += (_requestUrl.indexOf("?") == -1 ? "?" : "&");
                _requestUrl += name + "=" + value;
            }
        }
        return _requestUrl;
    }
}

2、确定各个请求。

function handleRequest() {

}

//  get请求带参数。
handleRequest.prototype.getDataUseGet = function(api, method, params) {
    var _url;
    var ajax = new Ajax();
    var token = sessionStorage.getItem('token');
    if(params) {
        _url = requstUrl.createUrl(api, method, params);
    } else {
        _url = requstUrl.createUrl(api, method);
    }
    return ajax.request(_url, {
        method: 'GET',
        params: params
    }, token);
}

//  get请求不带token
handleRequest.prototype.getDataUseGetWithoutToken = function(api, method, params) {
    var _url;
    var ajax = new Ajax();
    if(params) {
        _url = requstUrl.createUrl(api, method, params);
    } else {
        _url = requstUrl.createUrl(api, method);
    }
    return ajax.request(_url, {
        method: 'GET',
        params: params
    });
}

//  post请求带token
handleRequest.prototype.getDataUsePost = function(api, method, params) {
    var _url = requstUrl.createUrl(api, method);
    var token = sessionStorage.getItem('token');
    var ajax = new Ajax();
    console.log(createAjaxObj(_url, {
        method: 'POST',
        params: params
    }, token));
    return ajax.request(_url, {
        method: 'POST',
        params: params
    }, token);
}

//  post请求不带token
handleRequest.prototype.getDataUsePostWithOutToken = function(api, method, params) {
    var _url = requstUrl.createUrl(api, method);
    var ajax = new Ajax();
    return ajax.request(_url, {
        method: 'POST',
        params: params
    });
}

//  put请求带token
handleRequest.prototype.getDataUsePut = function(api, method, params) {
    var _url = requstUrl.createUrl(api, method);
    var token = sessionStorage.getItem('token');
    var ajax = new Ajax();
    return ajax.request(_url, {
        method: 'PUT',
        params: params
    }, token);
}

//  put请求不带token
handleRequest.prototype.getDataUsePutWithOutToken = function(api, method, params) {
    var _url = requstUrl.createUrl(api, method);
    var ajax = new Ajax();
    return ajax.request(_url, {
        method: 'PUT',
        params: params
    });
}

//  delete请求带token
handleRequest.prototype.deleteData = function(api, method, params) {
    var _url = requstUrl.createUrl(api, method);
    var token = sessionStorage.getItem('token');
    var ajax = new Ajax();
    return ajax.request(_url, {
        method: 'DELETE',
        params: params
    }, token);
}

这个方法感觉可以再次进行封装。

三、使用

1、使用代码

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>

	<body>
	</body>
	<script src="ip.js" type="text/javascript"></script>
	<script src="xhr.js" type="text/javascript"></script>
	<script src="request.js" type="text/javascript"></script>
	<script type="text/javascript">

		var data = {
			"captcha": "string",
			"password": "string",
			"username": "string"
		};

		var test = new handleRequest();
		test.getDataUsePostWithOutToken('LOGIN', 'login',data).complete(function(result) {
			console.log(result)
		})
	</script>

</html>

2、结果

成功发起请求。

完整代码点击查看

以上。

猜你喜欢

转载自blog.csdn.net/Bonny722/article/details/84062345