ica*_*ats 6 error-handling jquery json extending
我可能会偏离正轨,但我想知道是否可以使用JQuery 预过滤器功能并在Ajax Success中分析响应数据,并根据我返回的JSON中某些元素的存在有条件地转发到error我的ajax调用中的事件处理程序(错误消息).
如果这是为页面中的任何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?
}
});
});
Run Code Online (Sandbox Code Playgroud)
Ajax调用:
$.ajax({
type: "POST",
data: {
theData: "someData"
},
url: theUrl,
dataType: 'json',
cache: false,
success: function (data, textStatus, jqXHR) {
//do stuff on success
}
error: function ( jqXHR, textStatus, errorThrown ) {
//I want to do this stuff if data contains errors from server
}
});
Run Code Online (Sandbox Code Playgroud)
非常感谢!
ant*_*ioh 14
我是这样做的:我存储原始成功函数(特定于每个请求),然后附加另一个回调.如果它没有错误,我调用原始回调:
$.ajaxPrefilter(function( options, originalOptions, 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);
}
}
};
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6631 次 |
| 最近记录: |