Reputation: 5978
I would like to intercept and modify data from the server before the ajax success callback is executed
I have this code:
jquery.ajaxPrefilter(function (options, originalOptions, jqXHR) {
// Modify options, control originalOptions, store jqXHR, etc
});
and would like the equivalent:
jquery.ajaxPostfilter(function (dataComingFromServer) {
dataComingFromServer.applyMyModifications();
});
ajaxPostfilter does not exist though - is there another way of intercepting the response from the server before it reaches event handler:
This question is related to this one - but it was not answered: How can I intercept ajax responses in jQuery before the event handler?
Upvotes: 1
Views: 2763
Reputation: 5978
If you want to handle the data coming back from the server before the event handler, use datafilter:
jquery.ajaxSetup({
dataFilter: function (data, type) {
//modify the data
return data;
}
});
Upvotes: 1
Reputation:
If you want to use a standardised function to modify your data before the specific callback, you can use a pattern like this:
// Boilerplate to modify your data
function preprocess(data){
data.foo = "bar";
return data;
}
// Your specific handlers
function logdata(data){
console.log(data);
}
function writedata(data){
document.write(data);
}
// AJAX requests
$('#foo').load('url1', function(data) {
logdata(preprocess(data));
});
$('#bar').load('url2', function(data) {
writedata(preprocess(data));
});
Of course, this can be baked into a method that wraps the traditional .ajax
, making it more convenient to use.
Note that the dataFilter
option pointed out by KevinB serves a similar purpose, but it is limited to the .ajax
method. If you wanted to set a global filter for AJAX requests, you would use:
$.ajaxSetup({
dataFilter: preprocess
});
Upvotes: 1