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比较多的看情况下,项目中会出现过多的类似代码,维护起来相当麻烦,样板式的代码过多,不利于代码的可读性。
二:对于这种后台异步交互的访问代码,我们可以通过对业务数据访问的代码封装来进行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | 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 }); } }; |
这样封装以后,我们就可以通过对象的方式来获取后端业务数据。这也是前端面向对象的处理方式。例如:
1 2 3 4 5 6 7 8 9 10 11 | 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对象来进行前段错误提示。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步