web前端与后台数据访问的对象封装

前言:通常情况下,在不使用angularJS/nodeJS/react等这类完整性的解决方案的js时,前端与后台的异步交互都是使用Ajax技术进行解决

一:作为java web开发工程师可能以下代码是刚开始的阶段最普遍的写法

 1 $.ajax({
 2             cache: false,
 3             type: 'GET',
 4             url: this.rootUrl + '?' + $.param(param),
 5             dataType: "json",
 6             success: function(data){
 7 
 8             },
 9             error: function(){
10 
11             }
12 });

如果业务系统稍微复杂,CRUD比较多的看情况下,项目中会出现过多的类似代码,维护起来相当麻烦,样板式的代码过多,不利于代码的可读性。

二:对于这种后台异步交互的访问代码,我们可以通过对业务数据访问的代码封装来进行。

function Service(url) {
    this.rootUrl = url;

    this.errorHandler = function (jqXHR) {
        var response = jqXHR.responseJSON;
        if (response != null) {
            if (!response.success && response.errCode === MSG_SERVER_RESPONSE_NO_USER) {
                $(".close").click();
                window.location.href = "index.html";
            } else {
                if (response.msg != null) {
                    Dialog.showMsg("错误代码:" + response.errCode + ",信息:" + response.msg);

                } else {
                    Dialog.showAlert("错误代码:" + response.errCode + ",信息:服务器异常");
                }
            }
        } else {
            Dialog.showAlert("服务器异常");
        }
    };

}
Service.prototype = {

    constructor: Service,
    //find
    getAll: function (param, callback) {
        $.ajax({
            cache: false,
            type: 'GET',
            url: this.rootUrl + '?' + $.param(param),
            dataType: "json",
            success: callback,
            error: this.errorHandler
        });
    },

    //find
    getAllAsync: function (param, callback) {
        $.ajax({
            cache: false,
            type: 'GET',
            url: this.rootUrl + '?' + $.param(param),
            dataType: "json",
            success: callback,
            async: false,
            error: this.errorHandler
        });
    },

    //find data by id
    getById: function (id, data, callback) {
        if (typeof data === "function") {
            callback = data;
            data = null;
        }
        $.ajax({
            cache: false,
            type: 'GET',
            url: this.rootUrl + '/' + id,
            data: data,
            dataType: "json",
            success: callback,
            error: this.errorHandler
        });
    }
};

  这样封装以后,我们就可以通过对象的方式来获取后端业务数据。这也是前端面向对象的处理方式。例如:

    var entService = new Service("../service/ba/enterprise");
    var userData = {
        "id": currentEnt.id
    };
    var successCallback = function (data) {
        resoleEntViewAll(data.data);
    };
    var errorCallBack = function () {
        return null;
    };
    entService.getById(userData.id, userData, successCallback);

  首先,通过new 一个自定义的Service,请求参数与正确返回的函数、错误返回的函数通过参数传递,在此处,我的所有错误处理方法都是调用同一个通用的错误处理函数。正确返回的回调函数,由于业务不同,在调用时分别指定,此处我的错误处理回调函数中使用了BootstrapDialog插件封装的自定义的错误弹框Dialog对象来进行前段错误提示。

 

posted @ 2016-03-23 22:05  HEWU  阅读(3346)  评论(1编辑  收藏  举报