我可能会偏离正轨,但我想知道是否有可能使用
JQuery
prefilter功能并分析Ajax Success中的响应数据,并根据我存在的某些元素有条件地转发到我的ajax调用中的错误事件处理程序返回JSON(错误消息).
如果这是为页面中的任何ajax函数全局设置的话会很好.
也许这不是解决这个问题的最好方法;如果有人有其他想法,请告诉我!
预滤器:
//only run prefilter on ajax calls expecting JSON back in response,would this
//be the right way to do this?
$.ajaxPrefilter( "json",function( options,originalOptions,jqXHR ) {
jqXHR.success(function(data,textStatus,jXHR) {
if( hasErrors(data) ) {
//forward to error event handler?
}
});
});
Ajax调用:
$.ajax({
type: "POST",data: {
theData: "someData"
},url: theUrl,dataType: 'json',cache: false,success: function (data,jqXHR) {
//do stuff on success
}
error: function ( jqXHR,errorThrown ) {
//I want to do this stuff if data contains errors from server
}
});
非常感谢!
解决方法
我是这样做的:我存储原始成功函数(特定于每个请求),然后附加另一个回调.如果它没有错误,我调用原始回调:
$.ajaxPrefilter(function( options,jqXHR ) {
var originalSuccess = options.success;
options.success = function (data) {
if(hasErrors(data)) {
//forward to error event handler or redirect to login page for example
}
else {
if (originalSuccess != null) {
originalSuccess(data);
}
}
};
});