首页 > 代码库 > 模块化管理ajax

模块化管理ajax

  web前端通过ajax调用后台接口的数据,当项目比较大、接口比较多时,零散的ajax调用会使项目看上去非常凌乱,而且重复调用的几率高。

  所以我推荐在工作时将ajax进行统一的封装,将接口进行统一的管理。

  首先,在顶层js中封装ajax的基本方法。

var ajaxDataController = function () {
    //打印ajax错误日志
    function printLog(result, url, params, response) {
        console.error(‘AJAX 请求异常 - %s\n错误信息:\n%c%s\n%c请求链接:%s\n%c请求参数:%c%s\n%c返回数据:%c%s‘,
            ‘color:red;‘,
            result,
            ‘color:#333;‘,
            ‘color:blue‘,
            url,
            ‘color:#333;‘,
            ‘color:green‘,
            JSON.stringify(params),
            ‘color:#333;‘,
            ‘color:#643A3A‘,
            response)
    }

    function dataHandle(url, params, callback, async, method) {

        if (!method) {
            throw ‘method 参数未设置‘
        }

        if ((typeof params) === ‘function‘) {
            callback = params
            params = null
        }

        params = params || {};
        params = $.extend({ date: new Date().getTime().toString() }, params);
        async = async == null ? true : async;

        var ERROR_PROCESS_MODE = 0;

        if (typeof (params.ERROR_PROCESS_MODE) != "undefined") {
            if (params.ERROR_PROCESS_MODE==1) {
                ERROR_PROCESS_MODE = 1;
                try {
                    delete params.ERROR_PROCESS_MODE;
                } catch (e) {

                }
               
            }
        }

        $.ajax({
            async: async,
            url: url,
            dataType: ‘json‘,
            data: params,
            type: method,
            success: function (result, textStatus, xhr) {
                if (result.success === false) {
                    printLog(result, url, params, xhr.responseText)
                }
                switch (result.status) {
                    case 200:
                        callback(result);
                        break;
                    case 400:
                        if (window.parent) {
                            alert(result.errorMessage);
                        } else {
                            alert(result.errorMessage);
                        }
                        break;
                    case 511:
                        //未登录
                        callback(result);
                        break;
                    case 512:
                        if (ERROR_PROCESS_MODE!=1) {
                            if (window.parent) {
                                alert(result.errorMessage);
                            } else {
                                alert(result.errorMessage);
                            }
                        }
                        callback(result);
                        break;
                    case 513:
                        callback(result);
                        break;
                    default:
                        //console.log(typeof xhr.responseText);
                        if(xhr.responseText.indexOf("<!DOCTYPE html>")!=-1){
                            result={status:511,errorMessage:"登录超时,请重新登录",resultObject:null};
                            callback(result);
                            break;
                        }
                        if (window.parent) {
                            alert("系统出现异常,请稍候再试");
                        } else {
                            alert("系统出现异常,请稍候再试");
                        }
                        
                        callback(result);
                        break;
                }

            },
            error: function (xhr, textStatus, error) {

                if (window.parent) {
                    alert("系统出现异常,请稍候再试");
                } else {
                    alert("系统出现异常,请稍候再试");
                }
                printLog(xhr.status, textStatus + ‘ - ‘ + error, url, params, xhr.responseText);
            }
        });
    }

    return {
        post: function (url, params, callback, async) {
            dataHandle(url, params, callback, async, ‘post‘);
        },
        put: function (url, params, callback, async) {
             dataHandle(url, params, callback, async, ‘put‘);
         },
         del: function (url, params, callback, async) {
             dataHandle(url, params, callback, async, ‘delete‘);
         },
        get: function (url, params, callback, async) {
            dataHandle(url, params, callback, async, ‘get‘);
        }
    };
};

 然后,在模块中加入可供调用的接口的集合。

 1 var myController = {
 2     _ajaxHander: ajaxDataController(),
 3     _url: {
 4         //所有的接口地址
 5         POST_REPORT1: ‘/report/report1‘,
 6 
 7         POST_REPORT2: ‘/report/report2‘,
 8 
 9         POST_REPORT3: ‘/report/report3‘
10     },
11 
12    Report1 : function(params,callback, async) {
13 
14         this._ajaxHander.post(this._url.POST_REPORT1, params,                     function(data) {
15             callback(data);
16         }, async);
17     },
18 
19    Report2 : function(params,callback, async) {
20 
21         this._ajaxHander.post(this._url.POST_REPORT2, params,                     function(data) {
22             callback(data);
23         }, async);
24     },
25 
26    Report3 : function(params,callback, async) {
27 
28         this._ajaxHander.post(this._url.POST_REPORT3, params,                          function(data) {
29             callback(data);
30         }, async);
31     }
32     
33 }
34     

 

最后,我们就可以直接调用相应的接口了。

 1     function loadReport1(params) {
 2         myController.Report1(params, function (data) {
 3             if (data.status == 511) {
 4             
 5             }
 6             if(data.status==200 && data.resultObject!=null){
 7             
 8             }else {
 9             
10             }
11         });
12     }

 

  

模块化管理ajax