原生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、结果

成功发起请求。

完整代码点击查看

以上。

原文地址:https://segmentfault.com/a/1190000017006833


更多专业前端知识,请上 【猿2048】www.mk2048.com
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值