My ajaxwrapper tool
Until recently, when I write ajax call, always write like below:
$.ajax({ type: "post", datatype: "json", url: "someurl", success: function (data) { //some logic } });
and repeat everywhere... Until some day: so much redundant code!
Fournately, the "ajaxwrapper" tool can resolve this problem. ^.^
By using "ajaxwrapper", the code will be changed like this:
a2d.core.ajax.ajaxwrapper("ajaxDefinationId", { userId: 100 }, function(result){ //some logic }).call();
I believe you'v found something missed--> we should define "ajaxDefinationId" first, like below:
a2d.core.ajax.ajaxwrapper.setup.add({ id: "ajaxDefinationId", method: "post", url: "testurl.aspx" });//we may extend here, add much more parameters like headers, etags, cache, etc...
Explain- core code:
a2d.core.ajax.ajaxwrapper = function (id, data, callback) { var defaultConfig = { id: null, data: null, callback: null }; var realConfig = $.extend(defaultConfig, { id: id, data: data, callback: callback }); var setupConfig = a2d.core.ajax.ajaxwrapper.setup.find(realConfig.id); var ajaxCall = function () { $.ajax({ url: setupConfig.url, type: setupConfig.method, async: true, cache: false, data: realConfig.data, dataType: "json", success: realConfig.callback, error: a2d.core.exception.service.takeoverFunction(function () { throw new kxtx.core.exception("ajax error"); }) }); } return { call: ajaxCall }; };
Code is simple. First, it search ajax's global defination & current definatio, and then invoke jquery's ajax method.
Let's look error handler: a2d.core.exception.service.takeoverFunction, this function can add a wrapper on a function. When an error throw in function, takeoverFunction will catch it, and process it. See below:
a2d.core.exception.service.takeoverFunction = function (fn) { var newHandler = function () { try { fn.call(fn, arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6], arguments[7], arguments[8], arguments[9], arguments[10]); } catch (ex) { if (ex instanceof a2d.core.exception) { a2d.core.events.service.publish("a2d.core.exception:occurred", ex); } else { alert("未知exception类型"); } } }; return newHandler; }
Code is still simple. Core code is "try/catch"-->a2d.core.events.service.publish("a2d.core.exception:occurred", ex);
AhHa, finally, we found the error was published by a2d framework. Depend on this mechanism, the concrete impl be decopouled by pub/sub pattern, we can subscribe this event flexible.
The tool has been integrated into A2DFramework.
心怀远大理想。
为了家庭幸福而努力。
商业合作请看此处:https://www.magicube.ai
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】