I may be way off course, but I was wondering if it's possible to use the JQuery prefilter functionality and analyze the response data in an Ajax Success and conditionally forward to the error
event handler in my ajax
calls based on the existence of certain elements in my returned JSON (error messages).
It would be nice if this was globally set for any ajax function in the page.
Maybe this isn't the best way to go about this; if anyone has an alternative idea, please let me know!
The prefilter:
//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 call:
$.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
}
});
Thank you so much!
Here's how I do it: I store the original success function (specific for each request), and then attach another callback. If it didn't have errors, I call the original callback:
$.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);
}
}
};
});
精彩评论