• 首页
  • /
  • 技术分享
  • /
  • 前端外包-前端外包是一门艺术之JavaScript封装函数列表(一)
科技发展无界,未来互联网产业将超越我们的想象
前端外包-前端外包是一门艺术之JavaScript封装函数列表(一)2019-05-27
前端外包-前端外包是一门艺术之JavaScript封装函数列表(一) 145

普通项目(Bootstrap+jQuery)创建全局文件app.js进行封装函数+设置全局常量+拦截

var app = {
  http: function (options, success, error) {
   //函数内容
  },
  imgHttp: function (options, success, error) {
   //函数内容
  }
}

ajax 封装

new Promise es6方法 需配合polyfill解决兼容问题

http: function (options) {
    const promise = new Promise(function(resolve, reject) {
        $.ajax({ 
            type: options.method || 'get', 
            url: hosts +  options.url,
            dataType : 'json',
            contentType : 'application/json; charset=utf-8',
            data :  JSON.stringify(options.data),
            headers: options.headers,
            xhrFields: {
                withCredentials: true
            },
            success: function(res){
                // 通过返回状态码进行成功失败回调,如接口返回格式混乱则无需判断直接成功回调
                if (res.bizCode === '200') {
                    // 成功回调
                    resolve((options.sCode) ? res.bizCode : res.bizValue)
                } else {
                    // 失败回调
                    reject((options.code) ? res.bizCode : res.bizAlertMsg)
                }
            }, 
            error: function(){ 
                // 失败回调
                reject('网络错误')
            } 
        });
    })
    return promise
}
// 调起执行
app.http({
    url: "/api",
    method: "post",
    data: data
}).then( function (data) {
   // 成功
}).catch( function (res){
   //失败
})

无兼容问题封装

http: function (options, success, error) {
    $.ajax({
        type: options.method || 'get',
        dataType: 'json',
        url: host + options.url,
        traditional: options.traditional,
        contentType: 'application/x-www-form-urlencoded',
        data: options.data,
        headers: {
            'UTOKEN': token
        },
        success: function (res) {
            // 成功回调
            if (success) success(res);
        },
        error: function (err) {
            // 失败回调
            if (error) error(err);
        }
    });
}
app.http({
    method: 'GET',
    url: '/logout/',
    data: {
        page: 1,
        page_size: 10
    }
}, function (res) {
   // 成功
}, function(err) {
   // 失败
})

 

30 +
专业成员
50 +
覆盖城市
300 +
全球客户
1000 +
完成项目
选择联系我们
小草互联,您值得信赖的合作伙伴!
联系我们