我有很多 JavaScript/jQuery 代码块来处理页面中的异步数据处理。每个代码块都有三个函数(代码仅供说明目的,不完整):
encapsulates
$.ajax
call:function doSomething(data){ // do some preprocessing $.ajax({}); // some JQuery Ajax operation that accepts data // do some postprocessing return false; }
handles the response:
function handleResponse(result){ // process the result return false; }
handles any error:
function handleError(XMLHttpRequest, textStatus, errorThrown){ // gracefully handle the Error and present relevant information to user return false; }
我想可能有不同的方法可以解决这个问题。
- 可以拥有一个可以在Ajax调用中重复使用的错误处理程序(显而易见)。
- 可以重新使用某些响应处理程序,但这会很麻烦,因为响应根据调用而异。
- 也许创建某种原型对象以提供基本功能,并具有用于错误处理的静态方法(JavaScript中是否可以做到这一点?)。