Simplest way to post-process the result of a jQuery ajax request?
Suppose I have a function fancyParse
intended to take the response returned by the server and turn it into something else. This function throws if the response makes no sense whatsoever, or if it has a special "internal error" flag set.
I'd like to chain this function into a $.post
call to get a new Deferred
. This new deferred would fail if the request fails, or if fancyParse
throws. It would succeed if the request succeeds and fancyParse
succeeds, and, important开发者_高级运维ly, will pass the result of fancyParse
to its success callbacks.
The perfect solution would look something like this:
$.post('/url', etc).postprocess(fancyParse)
.done(my_done_handler)
.fail(my_fail_handler);
Is something like this already available, or do I need to write such a postprocess
myself?
You can create you own deferred object:
$.postProcess = function(addr,test) {
var dfd = $.Deferred(); // create deferred object
$.post(addr) // make ajax call
.success( function(response) { // if ajax is OK
if (test) { // Your filter test
dfd.resolve("OK"); // if test is passed, call done()
} else {
dfd.reject("Bad test"); // otherwise call reject
}
})
.error(function() { // on ajax error
dfd.reject("Error"); // reject
});
return dfd.promise(); // return deferred object
};
//$.postProcess('/echo/json/',true) // to test good case
//$.postProcess('/echo/json/',false) // to test bad test
$.postProcess('/echo/error/',true) // to test bad ajax
.done( function(msg){
alert('ok:'+msg);
})
.fail( function(msg){
alert('fail:'+msg);
});
http://jsfiddle.net/bouillard/FRsjV/
dataFilter
function can be used to process data. You pass it with your request.
http://api.jquery.com/jQuery.ajax/
$.ajax({
...,
dataFilter: function (data, type) {
// do something with data and return it
return data.toLowerCase();
}
})
精彩评论